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


refering c++11 specification (5.1.2.13):

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

void f2() {     int = 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 use lambda-expression default value function argument?

e.g.

template<typename functor> void foo(functor const& f = [](int x){ return x; }) { } 

yes. in respect lambda expressions no different other expressions (like, say, 0). note deduction not used defaulted parameters. in other words, if declare

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

then foo(0); call foo<int> foo() ill-formed. you'd need call foo<int>() explicitly. since in case you're using lambda expression nobody can call foo since type of expression (at site of default parameter) unique. can do:

// perhaps hide in detail namespace or such auto default_parameter = [](int x) { return x; };  template<     typename functor = decltype(default_parameter) > void foo(functor f = default_parameter); 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -