5

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.

1

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That's interesting. Its not quite what I'm looking for, because the parameter type deduced is a pointer to a function - so it couldn't inlined for example, unlike with a Functor object as per my code above. Still I'm up-voting it, because you're showing me a way you can pass only the function template rather than the function itself (i.e. some_function rather than some_function<MyType>) and it actually works as you would expect (I've compiled a slightly modified version of the above)
@Smeeheey modern compilers are really good at inlining function pointers, especially when used in a static context. Play around on compiler explorer and you'll see that GCC can inline function pointers used like above even in the oldest version they have available. Compiler internals don't care at all about the language-level differences between e.g. reference and pointer, or static member vs. free function.
@Leushenko you're quite right, I used the compiler explorer to verify that this is indeed the case (an excellent tool BTW). I'm accepting the above answer on that basis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.