I need to call a template function or an overloaded function for each element in an arbitrary tuple. To be precise, I need to call this function for elements, as they are specified in the tuple.
For example. I have a tuple std::tuple<int, float> t{1, 2.0f}; and functional
class Lambda{ public: template<class T> void operator()(T arg){ std::cout << arg << "; "; } };
I need an Apply structure / function that, if called as Apply<Lambda, int, float>()(Lambda(), t) , will give:
1; 2.0f;
and NOT 2.0f; 1; 2.0f; 1; .
Please note that I know the solution if a package of "raw" parameters is passed to the function, and I know how to do this for tuples in the reverse order. But the following attempt to partial specialize Apply not performed:
template<class Func, size_t index, class ...Components> class ForwardsApplicator{ public: void operator()(Func func, const std::tuple<Components...>& t){ func(std::get<index>(t)); ForwardsApplicator<Func, index + 1, Components...>()(func, t); } }; template<class Func, class... Components> class ForwardsApplicator < Func, sizeof...(Components), Components... > { public: void operator()(Func func, const std::tuple<Components...>& t){} }; int main{ ForwardsApplicator<Lambda, 0, int, float>()(Lambda{}, std::make_tuple(1, 2.0f)); }
The code compiles, but only the first argument is printed. However, if I replace the ForwardsApplicator specialization with
template<class Func, class... Components> class ForwardsApplicator < Func, 2, Components... >{...}
it works correctly - but, of course, only for tuples of length 2. How can I do this - if possible, elegantly - for tuples of arbitrary length?
EDIT: Thanks guys for your answers! All three are really straightforward and explain the problem from all possible points of view.