I would like to have a default lambda for a functor argument in my function.
I am aware it is possible using a struct
and operator()
like this:
struct AddOne {
int operator()(int a) {
return a+1;
}
};
template <typename Functor = AddOne>
int run_old(int x, Functor func = AddOne())
{
return func(x);
}
But I was wondering if there was a modern way, given the changes in the standard in either c++14/17/20, to make this work?
template <typename Functor>
int run_new(int x, Functor func = [](int a){ return a+1; })
{
return func(x);
}
I'm not sure what one would use as the default type to Functor, or if there is syntax i'm unaware of.
https://godbolt.org/z/Hs6vQs
You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };
A C++ functor (function object) is a class or struct object that can be called like a function. It overloads the function-call operator () and allows us to use an object like a function.
Like function default arguments, templates can also have default arguments.
A function object, or functor, is any type that implements operator(). This operator is referred to as the call operator or sometimes the application operator. The C++ Standard Library uses function objects primarily as sorting criteria for containers and in algorithms.
From C++11 you can already do that:
template <typename Functor = int(int)>
int run_new(int x, Functor func = [](int a){ return a+1; })
{
return func(x);
}
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