【发布时间】:2013-09-24 04:54:11
【问题描述】:
在堆栈溢出问题Redefining lambdas not allowed in C++11, why?中,给出了一个无法编译的小程序:
int main() {
auto test = []{};
test = []{};
}
问题已得到解答,一切似乎都很好。然后是Johannes Schaub 和an interesting observation:
如果您在第一个 lambda 之前添加
+,它就会神奇地开始工作。
所以我很好奇:为什么以下工作有效?
int main() {
auto test = +[]{}; // Note the unary operator + before the lambda
test = []{};
}
【问题讨论】:
-
有趣的是,对于捕获 lambda,它不起作用。
-
@MatthieuM。因为捕获 lambdas 不会衰减为函数指针!
;) -
另一个
+sourcery 紧随其后。在 GCC 上试试这个:struct foo { static const int n = 100; }; int main() { return std::max(0, +foo::n); }。如果您删除+它无法链接,这是符合标准的行为。 VS2010 连接起来没有问题(即使没有+)。 -
让我们添加更多魔法:
auto test = *[]{};(注意x在这里仍然是一个函数指针,我认为由于衰减)然后..auto test = +*[]{};。当然,您可以无限重复此操作:auto test = *+*+*+[]{};。还有我最喜欢的:auto test = +*??(:>()<%??>;
标签: c++ c++11 lambda operator-overloading language-lawyer