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).
Defaults in Python Lambda ExpressionIn Python, and in other languages like C++, we can specify 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.
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.
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.
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); }
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With