c++ - 是否可以将 lambda 函数用于模板参数?

标签 c++ c++11 lambda

我正在查看 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/

相关文章:

c++ - OpenSSL,从 CString 读取公共(public) RSA key

c++ - 更改比较函数以根据配对 vector 的第二个条目对绘图进行排序

c++ - 如何在 C++11 中处理互斥成员函数

c++ - 为什么这里的三元运算符与 if-else 不同?

c++ - 我可以在 Visual Studio 中的 Lambda 中定义模板化函数

java - 为什么类型参数比方法参数强

c++ - 为什么 ofstream 无法在 C++ 中打开文件?原因?

c++ - zlib 在缓冲区扩展时停止

c++ - 使用继承的 luabind 和 std::shared_ptr

python - 从 .apply() 更改为使用列表理解将一个数据框与一列列表与另一个数据框中的值进行比较的函数