我想选择取决于一些有条件的拉姆达,但是编译器,对于一些lambda表达式表示,该类型的lambda表达式不三元运算符的分支之间匹配。为什么在三元运算符分支之间返回lambdas适用于某些lambdas?
下面的代码编译:
int flag = 4;
auto result = flag % 2
? [](int x) {
return x + x;
}
: [](int x) {
return x * x;
};
但下面的2段不进行编译:
int flag = 4;
auto result = flag % 2
? [flag](int x) {
return x + flag;
}
: [flag](int x) {
return x - flag;
};
auto result2 = flag % 2
? [](auto x) {
return x + x;
}
: [](auto x) {
return x * x;
};
导致以下错误分别是:
test.cpp: In function 'auto f(int)':
test.cpp:8:9: error: operands to ?: have different types 'f(int)::<lambda(int)>' and 'f(int)::<lambda(int)>'
? [flag](int x) {
test.cpp: In function 'auto f(int)':
test.cpp:10:9: error: operands to ?: have different types 'f(int)::<lambda(auto:1)>' and 'f(int)::<lambda(auto:2)>'
? [](auto x) {
^
为什么做的最后一2个片段不能编译?
说“错误”时请附上确切消息。 –
顺便说一句,作为一种解决方法,你可以明确地将至少一个lambda转换为'std :: function'。 –
我该如何解决lambda具有'auto'参数的最后一个问题? –