简体   繁体   中英

Templated function pointer with arguments as template parameter

I can't get my code to compile. I want to be able to declare a function that takes another function (or a class with operator() defined, or lambda expression) as parameter, and this function has template arguments as well. Here's an example of what I want to do:

template <class T, T F> 
T execF(T a, T b) 
{ 
    return F(a, b); 
}

template <class T>
T add(T a, T b) 
{ 
    return a + b;
}

int main()
{ 
    std::cout << execF<int, add>(3,4) << std::endl;
}

Is it possible to do something like this in C++14?

It should be:

template <class T, T F(T, T)>
T execF(T a, T b)
{
    return F(a, b);
}

If you want to omit all template parameters, I suggest to stick with Some Programmer Dude's comment and accept the function as a function parameter:

template <typename T>
T execF(T a, T b, T f(T, T))
{
    return f(a, b);
}

template <typename T>
T add(T a, T b) { return a + b; }

int main(int , char **)
{
    auto x = execF(41.8f, 0.2f, add); //all params deduced in both functions
    std::cout << x << std::endl;

    x = execF(27, 15, add); //idem
    std::cout << x << std::endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM