Search code examples
c++templateslambdafunction-pointersfunction-templates

Passing a templated function as method argument without lambdas?


I did like to being able to use extFunction or std::max or std::min as argument for the square method without declaring a lambda :

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

class Stuff
{
public:
    template <typename F>
    int square(int num, int num2, F&& func) 
    {
        return func(num, num2);
    }
};

int main()
{
    Stuff s;
    std::cout << s.square(1, 2, std::max<int>) << std::endl;
    return 0;
}

But the compiler (gcc 11.1) is telling me that:

the function is ambiguous : "couldn't deduce template parameter 'F'"

Is there a simple way to do that without lambdas ?

EDIT:

maybe it would be interesting to show how to do this with lambdas :

std::cout << s.square(1,2,[](auto&& a, auto&& b){return std::max(a,b);}) << std::endl;
    
std::cout << s.square(1,2,[](auto&& a, auto&& b){return std::min(a,b);}) << std::endl;
    
std::cout << s.square(1,2,[](auto&& a, auto&& b){return extFunction(a,b);}) << std::endl;

Output :

Program returned: 0
Program stdout

2
1
1

Solution

  • You should not be taking the address of a standard library function. See in detail here:

    Can I take the address of a function defined in standard library?

    Therefore, there is no simple way other than, pack std::max into a function object(i.e. lambda, functor) or in a function.