Why do returning lambdas between branches of a ternary operator work on some lambdas?

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?

+4
source share
2 answers

The first snippet compiles because both lambdas are implicitly converted to int(*)(int), so the compiler can use this as the type of an expression ?:and therefore infer the type result.

( 2), (5.1.2/6 N4141), , 2- 3- operator?: , , .

3 , , , --, . T2(*)(T1), T1 - , , T2 - . : " " , .

+7

. , , . , , . , , .

, (non-campuring, non-templated) . lambdas, ponter-, .

+3

Source: https://habr.com/ru/post/1673769/


All Articles