Archie Gertsman Archie Gertsman - 4 years ago 237
C++ Question

C++11 Change `auto` Lambda to a different Lambda?

Say I have the following variable containing a lambda:

auto a = [] { return true; };

And I want
to return
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
variable to a different lambda. I'm relitively a beginner so I may be missing some knowledge about
or lambdas. Thanks.

Answer Source

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; };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download