Is it possible to apply a general function to tuple elements?

I found a for_each loop for tuples that just iterates through the elements and passes them to the function.

namespace std { template<int I, class Tuple, typename F> struct for_each_impl { static void for_each(const Tuple& t, F f) { for_each_impl<I - 1, Tuple, F>::for_each(t, f); f(get<I>(t)); } }; template<class Tuple, typename F> struct for_each_impl<0, Tuple, F> { static void for_each(const Tuple& t, F f) { f(get<0>(t)); } }; template<class Tuple, typename F> void for_each(const Tuple& t, F f) { for_each_impl<tuple_size<Tuple>::value - 1, Tuple, F>::for_each(t, f); } } 

.

 auto t = std::make_tuple(Foo(),Bar(),Baz()); std::for_each(t,[](???){}); 

Is it possible to have such a common function?

 std::for_each(t,[](T &&t){t.foo();}); 

In the end, I just want to have something that works with every tuple.

 std::get<0>(t).foo(); std::get<1>(t).foo(); std::get<2>(t).foo(); ... 

Maybe it's easier with macros?

+5
source share
1 answer

In C ++ 14, you can use the generic lambda expression:

 for_each(t, [] (auto&& t) { std::forward<decltype(t)>(t).foo(); }); 

In C ++ 11, you can declare your own functor:

 struct Lambda { template <typename T> void operator()(T&& t) const { std::forward<T>(t).foo(); } }; for_each(t, Lambda{}); 

or if instead you want to apply another function depending on what type of tuple element is currently being processed, then again a user functor is a way:

 struct Lambda { void operator()(const Foo& foo) const { foo.foo(); } void operator()(const Bar& bar) const { bar.bar(); } void operator()(const Baz& baz) const { baz.baz(); } }; for_each(t, Lambda{}); 

And as a note: do not define functions inside the std .

+9
source

Source: https://habr.com/ru/post/1206986/


All Articles