Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++0x lambda capture by value always const?

Is there any way to capture by value, and make the captured value non-const? I have a library functor that I would like to capture & call a method that is non-const but should be.

The following doesn't compile but making foo::operator() const fixes it.

struct foo {   bool operator () ( const bool & a )   {     return a;   } };   int _tmain(int argc, _TCHAR* argv[]) {   foo afoo;    auto bar = [=] () -> bool     {       afoo(true);     };    return 0; } 
like image 334
Zac Avatar asked May 14 '10 16:05

Zac


People also ask

Is Lambda capture a const?

By default, variables are captured by const value . This means when the lambda is created, the lambda captures a constant copy of the outer scope variable, which means that the lambda is not allowed to modify them.

Does Lambda capture reference by value?

Lambdas always capture objects, and they can do so by value or by reference.


1 Answers

Use mutable.

 auto bar = [=] () mutable -> bool .... 

Without mutable you are declaring the operator () of the lambda object const.

like image 70
Edward Strange Avatar answered Oct 13 '22 23:10

Edward Strange