C++11 – Change `auto` Lambda to a Different Lambda in C++11

autoc++c++11lambda

Say I have the following variable containing a lambda:

auto a = [] { return true; };

And I want a to return false later on. Could I do something along the lines of this?

a = [] { return false; };

This syntax gives me the following errors:

binary '=' : no operator found which takes a right-hand operand of type 
'main::<lambda_a7185966f92d197a64e4878ceff8af4a>' (or there is no acceptable conversion)

IntelliSense: no operator "=" matches these operands
        operand types are: lambda []bool ()->bool = lambda []bool ()->bool

Is there any way to achieve something like this? I would like to change the auto variable to a different lambda. I'm relitively a beginner so I may be missing some knowledge about auto or lambdas. Thanks.

Best Answer

Every lambda expression creates a new unique type, so the type of your first lambda is different from the type of your second (example). Additionally the copy-assignment operator of a lambda is defined as deleted (example) so you're doubly-unable to do this. For a similar effect, you can have a be a std::function object though it'll cost you some performance

std::function<bool()> a = [] { return true; };
a = [] { return false; };
Related Question