C ++ 11 lambda walkthrough link patterns

In gcc 4.5, the following code compiles and works as expected with -std=c++0x ,

 #include <stdio.h> template<typename H> void caller(H h) { h(); } int main() { auto c = [](){ printf("A\n"); }; caller(c); caller([](){ printf("B\n"); }); return 0; } 

Print

 A B 

However, if caller determined to take the link,

 template<typename H> void caller(H &h) { h(); } 

The compiler complains

 test.cpp: In function 'int main()': test.cpp:61:34: error: no matching function for call to 'caller(main()::<lambda()>)' test.cpp:52:6: note: candidate is: void caller(H&) [with H = main()::<lambda()>] 

Why?

This seems to violate the idea of ​​lambdas providing value semantics for functions, but what's more, it means that I can't write some small inline functions that are a little annoying.

(Is this fixed in newer versions of gcc? I have not had the opportunity to check.)

Edit: I just found that it actually works:

 template<typename H> void caller(H *h) { (*h)(); } int main() { auto c = [](){ printf("A\n"); }; caller(&c); caller(&([](){ printf("B\n"); })); } 

I did not think that I could accept such a temporary address. Perhaps this solves the problem, although it is annoying that users pass functions to the closing address instead of a convenient link.

+4
source share
1 answer

You are trying to pass a temporary reference other than a constant. This will not work for any type.

Pass lambda using const link.

+6
source

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


All Articles