I want to choose a lambda depending on some conditional, but the compiler for some lambdas says that the lambda types do not match between the branches of the ternary operator.
The following code compiles:
int flag = 4;
auto result = flag % 2
? [](int x) {
return x + x;
}
: [](int x) {
return x * x;
};
but the following 2 snippets do not compile:
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;
};
leading to the following errors:
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) {
^
Why don't the last 2 snippets compile?
source
share