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

BЈо*_*вић 4 c++ lambda functional-programming initializer-list c++11

#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);
}
Run Code Online (Sandbox Code Playgroud)

上面的示例无法编译(使用g ++ 4.6.1)并出现下一条错误消息:

error: unable to deduce 'const std::initializer_list<const auto> []' from '{{}, {}, {}}'
Run Code Online (Sandbox Code Playgroud)

注释行正常工作(不指定函数类型).

这是g ++的怪癖吗?或者标准中是否有任何内容告诉上面不应该编译?

Cat*_*lus 8

你不能这样做.每个lambda都有一个独特的,无关的类型.如果你想要一组lambdas,你必须删除类型std::function:

std::function<void(int)> foo[] = {
    [](int) { ... },
    [](int) { ... },
    ...
};
Run Code Online (Sandbox Code Playgroud)

即使在

auto f1 = []{};
auto f2 = []{};
Run Code Online (Sandbox Code Playgroud)

这两种类型是不同的.

  • `[expr.prim.lambda]/3`准确地说明了这一点.不知道我怎么没看到它.谢谢. (2认同)