Last active
December 20, 2018 05:38
-
-
Save likev/4b5b57e24cfbe9ef64786008376e2448 to your computer and use it in GitHub Desktop.
function like std::for_each with tuple
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
test with vs2017 | |
*/ | |
#include<tuple> | |
#include<iostream> | |
// helper function to tuple_each a tuple of any size | |
template<class Tuple, typename Func, std::size_t N> | |
struct TupleEach { | |
static void tuple_each(Tuple& t, Func& f) | |
{ | |
TupleEach<Tuple, Func, N - 1>::tuple_each(t, f); | |
f(std::get<N - 1>(t)); | |
} | |
}; | |
template<class Tuple, typename Func> | |
struct TupleEach<Tuple, Func, 1> { | |
static void tuple_each(Tuple& t, Func& f) | |
{ | |
f(std::get<0>(t)); | |
} | |
}; | |
template<typename Tuple, typename Func> | |
void tuple_each(Tuple& t, Func& f) | |
{ | |
TupleEach<Tuple, Func, std::tuple_size<Tuple>::value>::tuple_each(t, f); | |
} | |
// end helper function | |
int main() | |
{ | |
auto tup = std::tuple<double, short, int, long long, double>(0, 10, 200, 3000, 400.01); | |
tuple_each(tup, [](auto& v) {std::cout << v << ' '; }); | |
std::cout << std::endl; | |
tuple_each(tup, [](auto& v) {v += 1; }); | |
tuple_each(tup, [](auto& v) {std::cout << v << ' '; }); | |
} | |
/* | |
Output: | |
0 10 200 3000 400.01 | |
1 11 201 3001 401.01 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
template <class F, class T>
void for_tuple(T &&tuple, F &&f)
{
auto for_args = [&](auto&& ...args)
{ return (void)(f(std::forward<decltype(args)>(args)), ...); };
std::apply(for_args, std::forward(tuple));
}