Search code examples
c++templatesc++14decltype

Neat way to parametrize function template with generic function pointer


Consider following case: I have

int bar1();
double bar2();

I want:

foo<bar1>(); // calls bar1, then uses its result.
foo<bar2>(); // calls bar2, then uses its result.

Naive way to write template foo() is to use additional parameter:

template <typename T, T (*f)()> void foo () {
  // call f, do something with result
}

This works, but I need to do ugly syntax:

foo<decltype(bar1()), bar1>(); // calls bar1, then uses its result

I want to write something pretty, like above, just foo<bar1>.

P.S. Please do not recommend to accept argument at runtime. I need compile time parametrization with function pointer only.

P.S. Sorry forget to mention: I am looking for C++14 solution. C++17 appreciated and I upvoted answer with C++17 solution, but project now builds with C++14 and I can not change it in nearest future.


Solution

  • In order to get

    foo<bar1>();
    

    You need template<auto> from C++17. That would look like

    int bar1() { return 1; }
    double bar2() { return 2.0; }
    
    template<auto function> void foo() { std::cout << function() << "\n"; }
    
    int main()
    {
        foo<bar1>();
        foo<bar2>();
    }
    

    Which outputs

    1
    2
    

    Live Example

    Before C++17 you have to specify the type as there is no auto deduction of the type of a non type template parameters.