A late answer but here is general solution with C++14 which works like the boost::fusion::for_each
but doesn't require Boost:
#include <tuple>
namespace detail {
template<typename Tuple, typename Function, std::size_t... Is>
void tuple_for_each_impl(Tuple&& tup, Function&& fn, std::index_sequence<Is...>) {
using dummy = int[];
static_cast<void>(dummy {
0, (static_cast<void>(fn(std::get<Is>(std::forward<Tuple>(tup)))), 0)...
});
}
}
template<typename Function, typename... Args>
void tuple_for_each(std::tuple<Args...>&& tup, Function&& fn) {
detail::tuple_for_each_impl(std::forward<std::tuple<Args...>>(tup),
std::forward<Function>(fn), std::index_sequence_for<Args...>{});
}
int main() {
tuple_for_each(std::tie(w1, w2, w3, w4, w5, w6, t1, t2, t3), [](auto&& arg) {
arg.show();
});
}
If you want to achieve more or less the same thing without the std::tuple
, you can create a single-function variant of the above code:
#include <utility>
template<typename Function, typename... Args>
void va_for_each(Function&& fn, Args&&... args) {
using dummy = int[];
static_cast<void>(dummy {
0, (static_cast<void>(fn(std::forward<Args>(args))), 0)...
});
}
int main() {
auto action = [](auto&& arg) { arg.show(); };
va_for_each(action, w1, w2, w3, w4, w5, w6, t1, t2, t3);
}
The drawback of the second example is that it requires to specify the processing function first, therefore doesn't have the same look like the well known std::for_each
. Anyway with my compiler (GCC 5.4.0) using -O2
optimization level, they produce the same assembly output.