操作を実行するために、それぞれ任意のタイプの N 個の変数を範囲指定する簡潔な方法は何ですか?
a
変数、b
、c
、がありd
、e
何らかの操作を実行してそれらすべてを調べたいとしましょう。
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;
});
}
以下を使用できます: (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))), ... );
}