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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With