Reputation: 7775
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.
Upvotes: 8
Views: 435
Reputation: 303087
Just for fun, in C++20 we have both (1) lambdas in unevaluated contexts and (2) lambdas without capture are default constructible. Combine those two and you get:
template <typename Functor = decltype([](int a){ return a+1; })>
int run_new(int x, Functor func = {})
{
return func(x);
}
Upvotes: 1
Reputation: 66200
The best I can imagine pass through a variable
static constexpr auto defFunc = [](int a){ return a+1; };
template <typename Functor = decltype(defFunc)>
int run_new(int x, Functor func = defFunc)
{
return func(x);
}
Upvotes: 0
Reputation: 23497
Alternatively to other questions, you can even avoid templates:
int run_new(int x, std::function<int(int)> func = [](int a){ return a + 1; })
{
return func(x);
}
Upvotes: 0
Reputation: 180630
Just add an overload for this.
template <typename Functor>
int run_new(int x, Functor func)
{
return func(x);
}
int run_new(int x)
{
return run_new(x, [](int a){ return a+1; });
}
Allows you to get around not beening able to have a lambda expression as a default function argument.
Upvotes: 3
Reputation: 122476
Not quite "modern" but you could use plain old overloading with a non-template method taking only a single parameter:
int run_new(int x)
{
return func(x,[](int a){ return a+1;}); // calls the template overload
}
Upvotes: 1
Reputation: 9715
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);
}
Upvotes: 8