#include <functional>
#include <iostream>
namespace{
//const std::function< void( const int ) > foo[] =
const auto foo[] =
{
[]( const int v ){ std::cout<<v<<std::endl; },
[]( const int v ){ std::cout<<v/2<<std::endl; },
[]( const int v ){ std::cout<<v/3<<std::endl; },
};
}
int main()
{
foo[1](5);
}
上面的示例无法编译(使用g ++ 4.6.1),并显示下一条错误消息:
error: unable to deduce 'const std::initializer_list<const auto> []' from '{{}, {}, {}}'
注释行正常工作(未指定函数类型)。
这是g ++的怪癖吗?或者标准中是否有任何内容告诉上面不应该编译?
答案 0 :(得分:8)
你不能这样做。每个lambda都有一个独特的,无关的类型。如果你想要一组lambda,你必须用std::function
:
std::function<void(int)> foo[] = {
[](int) { ... },
[](int) { ... },
...
};
即使在
auto f1 = []{};
auto f2 = []{};
两种类型不同。
答案 1 :(得分:2)
除了别人对lambdas具有唯一类型的说法之外,不允许使用auto
作为数组变量声明中的说明符。即使以下情况也是不正确的
auto x[] = { 1, 2, 3 }; // 'auto' disallowed