在 gcc 4.5 中,使用 -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;
}
打印,
A
B
但是,如果 caller
被定义为引用,
template<typename H>
void caller(H &h)
{
h();
}
编译器提示,
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()>]
为什么?
这似乎打破了 lambda 为函数提供值语义的想法,而且这意味着我不能内联编写某些小函数,这有点烦人。
(这在较新版本的 gcc 中已修复吗?我还没有机会测试。)
编辑:我刚刚发现以下内容确实有效:
template<typename H>
void caller(H *h)
{
(*h)();
}
int main()
{
auto c = [](){ printf("A\n"); };
caller(&c);
caller(&([](){ printf("B\n"); }));
}
我不认为我能够像那样获取临时地址。也许这样可以解决问题,尽管要求函数的用户传入闭包的地址而不是方便的引用很烦人。
最佳答案
您正在尝试通过非常量引用传递临时值。这不适用于任何类型。
改为通过 const 引用传递 lambda。
关于c++ - 通过模板化引用传递 C++11 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12305003/