2

操作を実行するために、それぞれ任意のタイプの N 個の変数を範囲指定する簡潔な方法は何ですか?

a変数、bc、がありde何らかの操作を実行してそれらすべてを調べたいとしましょう。

4

3 に答える 3

6

Boost.Hana とジェネリック ラムダを使用します。

#include <tuple>
#include <iostream>
#include <boost/hana.hpp>
#include <boost/hana/ext/std/tuple.hpp>

struct A {};
struct B {};
struct C {};
struct D {};
struct E {};

int main() {
    using namespace std;
    using boost::hana::for_each;

    A a;
    B b;
    C c;
    D d;
    E e;

    for_each(tie(a, b, c, d, e), [](auto &x) {
        cout << typeid(x).name() << endl;
    });
}

http://coliru.stacked-crooked.com/a/ccb37ec1e453c9b4

于 2014-04-23T05:51:41.097 に答える
4

以下を使用できます: (C++11) ( https://ideone.com/DDY4Si )

template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
    const int dummy[] = { (f(std::forward<Ts>(args)), 0)... };
    static_cast<void>(dummy); // avoid warning about unused variable.
}

Fファンクター (または一般的なラムダ (C++14)) を使用します。C++14 では次のように呼び出すことができます。

apply([](const auto &x) { std::cout << typeid(x).name() << std::endl;}, a, b, c, d, e);

C++17 では、折りたたみ式を使用すると、次のようになります。

template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
    (static_cast<void>(f(std::forward<Ts>(args))), ... );
}
于 2014-04-23T07:28:09.723 に答える