Friday 3 November 2023

C++ lambda pointers

 Every now and again I get surprised by C++. TIL that if you want to write:

    auto l = [] { std::cout << "I like goats\n"; };
    l();
    l = [] { std::cout << "I like boats\n"; };                                 
    l();       
then it doesn't work: the compiler complains
error: no match for ??operator=?? (operand types are ??main()::?? and ??void (*)()??)
You're trying to overwrite the lambda, and you can't. You want "l" to be a pointer. You can have this if you write
    void(*l)(void) = [] { std::cout << "I like goats\n"; };                                                  
but that's tedious: you have to remember the deeply confusing C function-pointer syntax; and when you're gaily tossing off complex lambda's in the middle of code, it's worse. But it turns out that you can write
    auto l = +[] { std::cout << "I like goats\n"; };                                   
and the "+" magically converts the lambda into a pointer-to. This stackoverflow post "explains" it. Fiddling around with std::function probably works too.

No comments:

Post a Comment