I can return a lambda from ternary operator if both the lambda doesn't capture anything.
 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);
This works fine.
But this doesn't
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);
The error is main.cpp:20:18: error: operands to ?: have different types 'main()::<lambda(int)>' and 'main()::<lambda(int)>' ? [&n] (int a) {std::cout << "First\n";}
I wonder why capturing the same variable changes the type of lambda?
Aucun commentaire:
Enregistrer un commentaire