C++11 将 `auto` Lambda 更改为不同的 Lambda? [英] C++11 Change `auto` Lambda to a different Lambda?
问题描述
假设我有以下包含 lambda 的变量:
Say I have the following variable containing a lambda:
auto a = [] { return true; };
我希望 a
稍后返回 false
.我可以做一些类似的事情吗?
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
有没有办法实现这样的目标?我想将 auto
变量更改为不同的 lambda.我是一个初学者,所以我可能缺少一些关于 auto
或 lambdas 的知识.谢谢.
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.
推荐答案
每个 lambda 表达式都会创建一个新的唯一类型,因此您的第一个 lambda 表达式的类型与第二个的类型不同 (示例).此外,lambda 的复制赋值运算符被定义为已删除(example),因此您双重无法做这个.对于类似的效果,您可以将 a
设为 std::function
对象,尽管这会降低性能
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; };
这篇关于C++11 将 `auto` Lambda 更改为不同的 Lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!