Skip to content

Instantly share code, notes, and snippets.

@likev
Last active December 20, 2018 05:38
Show Gist options
  • Save likev/4b5b57e24cfbe9ef64786008376e2448 to your computer and use it in GitHub Desktop.
Save likev/4b5b57e24cfbe9ef64786008376e2448 to your computer and use it in GitHub Desktop.
function like std::for_each with tuple
/*
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
*/
@BenzzzX
Copy link

BenzzzX commented Dec 20, 2018

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));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment