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 ++的怪癖吗?或者标准中是否有任何内容告诉上面不应该编译?
你不能这样做.每个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)
这两种类型是不同的.
| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |