我正在查看 std::unordered_map,发现如果我想使用字符串作为键,我必须创建一个包含仿函数的类。
出于好奇,我想知道是否可以使用 lambda 来代替它。
这是工作原件:
struct hf
{
size_t operator()(string const& key) const
{
return key[0]; // some bogus simplistic hash. :)
}
}
std::unordered_map<string const, int, hf> m = {{ "a", 1 }};
这是我的尝试:
std::unordered_map<string const, int, [](string const& key) ->size_t {return key[0];}> m = {{ "a", 1 }};
失败并出现以下错误:
exec.cpp: In lambda function:
exec.cpp:44:77: error: ‘key’ cannot appear in a constant-expression
exec.cpp:44:82: error: an array reference cannot appear in a constant-expression
exec.cpp: At global scope:
exec.cpp:44:86: error: template argument 3 is invalid
exec.cpp:44:90: error: invalid type in declaration before ‘=’ token
exec.cpp:44:102: error: braces around scalar initializer for type ‘int’
鉴于这些错误,lamba 似乎与仿函数有足够的不同,以至于它不是一个常量表达式。对吗?
最佳答案
lambda函数的传递方式是:
auto hf = [](string const& key)->size_t { return key[0]; };
unordered_map<string const, int, decltype(hf)> m (1, hf);
^^^^^^^^^^^^ ^^
passing type object
decltype(hf)
的输出是一个没有默认构造函数的类类型(被 =delete
删除)。所以,你需要通过 unordered_map
的构造函数传递对象,让它构造 lambda 对象。
关于c++ - 是否可以将 lambda 函数用于模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16763148/