c++ - 通过模板化引用传递 C++11 lambda

标签 c++ lambda c++11

在 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/

相关文章:

amazon-web-services - AWS Lambda 和网关 API 集成,返回状态代码 500

c++11 - 是全局变量 constexpr 的地址吗?

c++ - 当左值传递给 T&& 时,会发生什么?

C++ 使用 std::accumulate 生成 map<int,int>

c++ - 添加 curl 库 C++

涉及条件 (if) 的 python 映射函数 (+ lambda)

c++ - 参数列表中的 void_t 有效但不作为返回类型

c++ - 我无法理解下面文本中最后一段的含义

c++ - STL - 在 <algorithm> 中使用成员函数或函数?

c++ - 创建带变量的字符串