Pass a function as an explicit template parameter

c++, templates

Solution

The problem here is, `multiply` is not a type; it is a value but the function template `bar` expects the template argument to be a type. Hence the error.

If you define the function template as:

template <int (*F)(int,int)> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
    cout << F(x, y) << endl;
}

then it will work. See online demo : http://ideone.com/qJrAe

You can simplify the syntax using `typedef` as:

typedef int (*Fun)(int,int);

template <Fun F> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
    cout << F(x, y) << endl;
}

Problem

In the code example below, the call to `foo` works, while the call to `bar` fails. If I comment out the call to `bar`, the code compiles, which tells me the definition of `bar` itself is fine. So how would `bar` be called correctly? ``` #include <iostream> using namespace std; int multiply(int x, int y) { return x * y; } template <class F> void foo(int x, int y, F f) { cout << f(x, y) << endl; } template <class F> void bar(int x, int y) { cout << F(x, y) << endl; } int main() { foo(3, 4, multiply); // works bar<multiply>(3, 4); // fails return 0; } ```

Original source

Related problems