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.
We may use retrospective call to convert lambda to std::function:
After that we will be able to do (since 'a' is std::function type now ):
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 astd::function
object though it'll cost you some performanceA Lambda may be converted to a function pointer using the unary
+
operator like so:so long as the capture group is empty and it doesn't have
auto
arguments.1If you do this, you may assign different lambdas to the same variable as long as the lambdas all have the same signature.
In your case,
Live example on Coliru
would both compile and act as you expect.2 You may use the function pointers in the same way you would expect to use a lambda, since both will act as functors.
1. In C++14, you can declare lambdas with
auto
as the argument type, like[](auto t){}
. These are generic lambdas, and have a templatedoperator()
. Since a function pointer can't represent a templated function, the+
trick won't work with generic lambdas.2. Technically, you don't need the second
+
operator on the assignment. The lambda would convert to the function pointer type on assignment. I like the consistency, though.Since
C++17
you can have thestd::function
template parameter deduced thanks to Class template argument deduction. It even works with capturing lambdas:This comes in handy with more complex signatures and even more with deduced return types.
Each lambda has a different type so you cannot change it. You could use a std::function to hold an arbitrary callable object, that can be changed at will.