无法从初始化列表中的lambda推断出类型

时间:2012-05-21 07:57:39

标签: c++ lambda functional-programming c++11 initializer-list

#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 ++的怪癖吗?或者标准中是否有任何内容告诉上面不应该编译?

2 个答案:

答案 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