【发布时间】: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。
-
谢谢——这就是诀窍——现在我很困惑“默认启用”的警告信息是什么意思.....