简体   繁体   中英

Default argument for a functor in a templated parameter

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

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);
}

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.

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
}

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);
}

Obligatory godbolt .

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);
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM