I have the following code defining a Functor template and the function
running_op, which takes an array, it’s length and a functor to apply
to the list:
template <class Type>
struct SumFunctor {
Type sum;
SumFunctor() : sum(0) {};
Type operator()(Type next) {
return sum += next;
}
};
template <class Container, class Functor>
inline Container running_op(Container& container, Functor functor) {
transform(container.begin(), container.end(), container.begin(), functor);
return container;
}
This is used in the following way:
list<float> a({1,1,1,1});
running_op(a, SumFunctor<float>());
What I would like to be able to do to avoid having type the name of
the container in the instantiated functor is use it as so:
list<float> a({1,1,1,1});
running_op(a, SumFunctor);
Since the contained type of a can be found in the running_op template
using Container::value_type I would like to do something as follows
(which does not work) to instantiate the functor of appropriate type:
template <class Container, class Functor>
inline Container running_op(Container& container, Functor functor) {
typedef typename Container::value_type ContainerType;
transform(container.begin(), container.end(), container.begin(), functor<ContainerType>());
return container;
}
Is there any way that I can pass an
uninstantiated template to another template for later instantiation?
Is there a special keyword I should use other than class in the
template parameter list (template did not work in this case)? Really
I just want to pass in a symbol which is the functor template name; is
that possible?
You can use template templates.
If you want that certain syntax you can use macros, although I don’t recommend it.