【问题标题】:Compilation error on passing lambda expression to template function将 lambda 表达式传递给模板函数时出现编译错误
【发布时间】:2013-09-27 03:13:08
【问题描述】:

为什么我不能让模板函数接受 lambda 表达式?

在高低搜索之后——我认真地认为这会起作用,但是这个 C++ 代码;

template <typename F> int proc(const F& lam)
{
    return lam();
}
void caller()
{
    int i = 42;
    int j = proc( [&i]()->int{ return i/7; } );
}

我收到以下错误;

$ g++ x.cc
x.cc: In function ‘void caller()’:
x.cc:11:44: warning: lambda expressions only available with -std=c++0x or -std=gnu++0x [enabled by default]
x.cc:11:46: error: no matching function for call to ‘proc(caller()::<lambda()>)’
x.cc:11:46: note: candidate is:
x.cc:3:27: note: template<class F> int proc(const F&)

我在 linux 上使用 g++ 4.6.3 和 4.7.2

有人知道我必须做什么才能将 lambda 表达式作为参数传递给接收模板函数吗? -- 我不想使用 std::function -- 所以我唯一的选择是创建一个丑陋的仿函数模式。

更新: 尝试声明参数 const F& lam,但没有成功。 Update2: 添加了对编译器的调用...

【问题讨论】:

  • 你传递给编译器的标志是什么?
  • 无 -- 没有标志 -- 通过调用编译器更新问题...
  • 您必须在 g++ 4.7.2 中使用 -std=c++11 或在 g++ 4.6.3 中使用 -std=c++0x。
  • 谢谢——这就是诀窍——现在我很困惑“默认启用”的警告信息是什么意思.....

标签: c++ c++11 lambda


【解决方案1】:

由于 lambda 不是左值,您需要通过 const 引用传递它:

template <typename F> int proc(const F& lam)

确保在 g++ 4.7.2 中使用 -std=c++11 或在 g++ 4.6.3 中使用 -std=c++0x。

【讨论】:

  • 不幸的是,这并没有解决问题.. x.cc:11:46: 错误:没有匹配函数调用 'proc(caller()::)' x。 cc:11:46: 注意: 候选是: x.cc:3:27: 注意: template int proc(const F&)
  • 感谢@Vaughn -- 尝试剪切粘贴您的工作代码 -- 仍然有同样的问题 -- 怀疑是编译器版本问题 -- 您使用的是什么版本?
  • @Soren:我使用的是 g++ 4.7.2
  • 使用 -std=c++11 和 g++ 4.7.2 或 -std=c++0x 和 g++ 4.6.3。
猜你喜欢
  • 2022-07-23
  • 2018-02-12
  • 2019-09-02
  • 2017-03-07
  • 1970-01-01
  • 2013-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多