Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use a lambda-expression as the default value for a function argument?

Tags:

c++

c++11

lambda

Refering to the C++11 specification (5.1.2.13):

A lambda-expression appearing in a default argument shall not implicitly or explicitly capture any entity.
[ Example:

void f2() {
    int i = 1;
    void g1(int = ([i]{ return i; })()); // ill-formed
    void g2(int = ([i]{ return 0; })()); // ill-formed
    void g3(int = ([=]{ return i; })()); // ill-formed
    void g4(int = ([=]{ return 0; })()); // OK
    void g5(int = ([]{ return sizeof i; })()); // OK
}

—end example ]

However, can we also use a lambda-expression itself as the default value for a function argument?

e.g.

template<typename functor>
void foo(functor const& f = [](int x){ return x; })
{
}
like image 227
0xbadf00d Avatar asked Oct 12 '11 14:10

0xbadf00d


People also ask

Can Python lambda have default arguments?

Defaults in Python Lambda ExpressionIn Python, and in other languages like C++, we can specify default arguments.

When a lambda function has only one parameter What is the default name?

Lambda expressions Like anonymous functions, lambda expressions allow no default parameters and cannot be called with named arguments. Since they are stored immediately as a function type like (Int, Int) -> Int , they undergo the same restrictions as function types referring to actual functions.

What is a lambda argument?

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.


1 Answers

Yes. In this respect lambda expressions are no different from other expressions (like, say, 0). But note that deduction is not used with defaulted parameters. In other words, if you declare

template<typename T>
void foo(T = 0);

then foo(0); will call foo<int> but foo() is ill-formed. You'd need to call foo<int>() explicitly. Since in your case you're using a lambda expression nobody can call foo since the type of the expression (at the site of the default parameter) is unique. However you can do:

// perhaps hide in a detail namespace or some such
auto default_parameter = [](int x) { return x; };

template<
    typename Functor = decltype(default_parameter)
>
void foo(Functor f = default_parameter);
like image 186
Luc Danton Avatar answered Oct 18 '22 22:10

Luc Danton