Tob*_*ann 4 c++ lambda c++11 c++14
在以下最小示例中:
int main()
{
const int foo = 1;
const auto a = foo == 1 ? [](){return 42;} : [](){return 4;};
const auto b = foo == 1 ? [foo](){return 42;} : [foo](){return 4;};
}
Run Code Online (Sandbox Code Playgroud)
a很好 b但是不是,因为:
<source>:5:29: error: incompatible operand types ('(lambda at <source>:5:31)' and '(lambda at <source>:5:53)')
const auto b = foo == 1 ? [foo](){return 42;} : [foo](){return 4;};
^ ~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
为什么会这样?以及如何b获得预期的?
捕获并不能使lambda变得唯一。根据定义,lambda类型已经是唯一的。但是,非捕获的lambda可以转换为函数指针,这在您的第一个示例中创建了通用类型。
您可以如下解决特定的示例:
const auto b = [foo](){ return (foo == 1) ? 42 : 4;};
Run Code Online (Sandbox Code Playgroud)