Passing a template member element to a template
I have a set of types templated for an integer N, and a class containing all types where N <= K and N> = 0, something like
template <int N> struct T { int i; }
template <int N> struct TContainer{
std::vector<T<N>> vec;
TContainer<N - 1> prev;
template <int target_n> TContainer<target_n> & get() { return prev.get(); }
template <> TContainer<N> & get<N>() { return *this; }
};
template <> struct TContainer<0>{
std::vector<T<N>> vec;
template <int target_n> TContainer<target_n> & get() { }
template <> TContainer<0> & get<0>() { return *this; }
};
class ContainsAll{
TContainer<K> my_data;
int my_instance_data;
};
Is it possible for ContainsAll to have some kind of foreach function that could use a template member function on every element for all N? Something like
template<int N>
void for_each(TContainer<N> & container, template_function){
for(auto it = container.vec.begin(); it != container.vec.end(); ++it){
template_function(*it);
}
for_each<K - 1>(container.prev, template_function);
}
template<> void for_each<0>(TContainer<0> & container, template_function){
for(auto it = container.vec.begin(); it != container.vec.end(); ++it){
template_function(*it);
}
}
So what can i do
template <int N> add_to_T(T<N> & in){
in.i += my_instance_data;
}
for_each(my_container, add_to_T);
+3
source to share
1 answer
You cannot pass a template function. But you can pass a struct instance (function object) that contains the template function, eg.
template <typename F>
void for_each(TContainer<0>& container, F f)
{
for (auto& t : container.vec)
f(t);
}
template <int N, typename F>
void for_each(TContainer<N>& container, F f)
{
for (auto& t : container.vec)
f(t);
for_each(container.prev, std::move(f));
}
struct TAdder {
template <int N>
void operator()(T<N>& t) const
{
t.i += N;
}
};
for_each(c, TAdder{});
+2
source to share