Reputation: 10326
Suppose I have a function with a template template parameter, like this:
template <template <class T> class F, typename P>
void applyFunction(int param)
{
F<P> fn;
fn(param);
}
The above can take an arbitrary class template for a Functor and apply it. So for example if I defined:
template<typename T>
struct SomeFunctor
{
void operator()(int param)
{
T::doStuff(param);
}
};
Then I could make the following call:
applyFunction<SomeFunctor, MyClass>(0);
But what I'd really like to do is to be able to pass function templates (rather than just class templates that define functors). So if I had something like this:
template<typename T>
void someFunction(int param)
{
T::doStuff(param);
}
Ideally I'd be able to do something like this:
applyFunction<someFunction, MyClass>(0);
Unfortunately as it stands this is not legal C++. Is there a way to do this that I'm missing? In other words pass a function template rather than a class template as a template template parameter? Conceptually I don't see why it shouldn't be possible.
Upvotes: 5
Views: 2646
Reputation: 8376
You could take a pointer to your function as template argument:
template < typename T, T (*F)(int) >
void apply_function(int param) {
F(param);
}
template < typename T >
T some_function(int param) {
T::doStuff(param);
}
int main() {
apply_function< float, some_function >(5);
}
In your case it would be:
apply_function< MyClass, some_function >(0);
then for example.
Upvotes: 6