Я могу вернуть лямбду из тернарного оператора, если оба лямбда ничего не захватывают.
auto lambda1 = 1==1
? [] (int a) {std::cout << "First\n";}
: [] (int a) {std::cout << "Second\n";};
auto lambda2 = 1==2
? [] (int a) {std::cout << "First\n";}
: [] (int a) {std::cout << "Second\n";};
lambda1(10);
lambda2(10);
Это прекрасно работает.
Но это не
int n = 10;
auto lambda3 = 1==1
? [&n] (int a) {std::cout << "First\n";}
: [&n] (int a) {std::cout << "Second\n";};
auto lambda4 = 1==2
? [&n] (int a) {std::cout << "First\n";}
: [&n] (int a) {std::cout << "Second\n";};
lambda3(10);
lambda4(10);
Ошибка main.cpp:20:18: error: operands to ?: have different types 'main()::<lambda(int)>' and 'main()::<lambda(int)>' ? [&n] (int a) {std::cout << "First\n";}
Интересно, почему при захвате одной и той же переменной изменяется тип лямбды?





8.4.5.1 Closure types [expr.prim.lambda.closure]
- The type of a lambda-expression (which is also the type of the closure object) is a unique unnamed non-union class type, called the closure type.
Итак, lambda3 и lambda4, имеющие захват, являются уникальными типами, которые отличаются друг от друга.
- The closure type for a non-generic lambda-expression with no lambda-capture whose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type’s function call operator.
lambda1 и lambda2 (без захвата) могут быть преобразованы в указатель на функцию и относятся к одному типу.
См. Пояснение stackoverflow.com/a/11406936/8769985