What's a succinct way of ranging through N variables, of any type each, to perform an operation?
Let's say I have variables a
, b
, c
, d
, e
and want to go through all of them performing some operation.
What's a succinct way of ranging through N variables, of any type each, to perform an operation?
Let's say I have variables a
, b
, c
, d
, e
and want to go through all of them performing some operation.
Use Boost.Hana and generic lambdas:
#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
You may use: (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.
}
With F
a functor (or a generic lambda (C++14)).
You may call it like this in C++14:
apply([](const auto &x) { std::cout << typeid(x).name() << std::endl;}, a, b, c, d, e);
In C++17, with folding expression, it would be:
template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
(static_cast<void>(f(std::forward<Ts>(args))), ... );
}
I love the range-based for loop in C++11:
#include <iostream>
struct S {int number;};
int main() {
S s1{1};
S s2{2};
S s3{3};
for (auto i : {s1, s2, s3}) {
std::cout << i.number << std::endl;
}
}