Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a lambda function as default argument

Tags:

c++

c++11

lambda

How do I assign a lambda as default argument? I would like to do this:

int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; }) {     return f(i); } 

but my compiler (g++ 4.6 on Mac OS X) complains:

error: local variable 'x' may not appear in this context 

EDIT: Indeed, this was a compiler bug. The above code works fine with a recent version of gcc (4.7-20120225).

like image 292
mavam Avatar asked May 17 '11 00:05

mavam


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.

Can functions have default arguments?

In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.

When lambda function has only one parameter what is 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 function with default argument?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


2 Answers

You could use overloading:

int foo(int i) {     return foo(i, [](int x) -> int { return x / 2; }); }  int foo(int i, std::function<int(int)> f) {     return f(i); } 
like image 180
Tim Sylvester Avatar answered Oct 05 '22 02:10

Tim Sylvester


This seems to be a bug in gcc; the standard permits lambda expressions in default parameters as long as nothing is captured.

The following seems to be everything the FDIS says about lambdas in default parameters, so any use other than what is forbidden here ought to be permitted by default.

C++11 FDIS 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 ]

like image 38
JohannesD Avatar answered Oct 05 '22 03:10

JohannesD