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.

Smeeheey
  • 9,906
  • 23
  • 39
  • 2
    Take a look at http://stackoverflow.com/q/15651488/3235496 (strictly related to your question) – manlio May 05 '16 at 14:01

1 Answers1

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.

tobspr
  • 8,200
  • 5
  • 33
  • 46
  • 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`) and it actually works as you would expect (I've compiled a slightly modified version of the above) – Smeeheey May 05 '16 at 13:02
  • 1
    @Smeeheey modern compilers are really good at inlining function pointers, especially when used in a static context. Play around on [compiler explorer](https://godbolt.org/#) 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. – Alex Celeste Mar 18 '18 at 23:05
  • @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. – Smeeheey Apr 16 '18 at 10:50