Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 911
Salgar Avatar asked Sep 04 '19 15:09

Salgar


People also ask

Can template parameters have default arguments?

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

What is functor in c++?

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.

Can we have default argument in fun template?

Like function default arguments, templates can also have default arguments.

What are function objects in c++?

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.


1 Answers

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);
}
like image 61
BiagioF Avatar answered Nov 13 '22 16:11

BiagioF