Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 496
fabien le corre Avatar asked Jul 28 '21 06:07

fabien le corre


People also ask

How do you pass a function as a template argument in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can lambdas be templated?

From the various lambda improvements, template parameters for lambdas are my favorite ones. Lambdas support with C++20 template parameters, can be default-constructed and support copy-assignment, when they have no state, and can be used in unevaluated contexts.

What is the use of lambda function in c++?

C++ Lambda expression allows us to define anonymous function objects (functors) which can either be used inline or passed as an argument. Lambda expression was introduced in C++11 for creating anonymous functors in a more convenient and concise way.

How do you pass a lambda function as an argument?

Passing Lambda Expressions as Arguments If you are passing an instance of a class as a parameter, you must specify the class name or the object class as a parameter to hold the object. In Java, there is no type for lambda expression.


Video Answer


1 Answers

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.

like image 94
JeJo Avatar answered Oct 19 '22 07:10

JeJo