Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否可以将lambda函数用于模板参数?_C++_C++11_Lambda - Fatal编程技术网

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

C++ 是否可以将lambda函数用于模板参数?,c++,c++11,lambda,C++,C++11,Lambda,我在查看std::unordered_映射时发现,如果我想使用字符串作为键,我必须创建一个包含函子的类 出于好奇,我想知道是否可以用lambda来代替这个 这是工作原件: struct hf { size_t operator()(string const& key) const { return key[0]; // some bogus simplistic hash. :) } } std::unordered_map<string const, in

我在查看std::unordered_映射时发现,如果我想使用字符串作为键,我必须创建一个包含函子的类

出于好奇,我想知道是否可以用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 }};

考虑到这些错误,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
auto-hf=[](字符串常量和键)->size_{return key[0];};
无序映射m(1,hf);
^^^^^^^^^^^^        ^^
传递类型对象

decltype(hf)
的输出是一个没有默认构造函数的类类型(它被
=delete
删除)。因此,您需要通过
unordered_map
的构造函数传递对象,让它构造lambda对象。

std::hash
专门用于
std::string
,如果您不想改进/更改hash,则无需自己提供某些内容。另外,想想你在做什么:
std::unordered_map
需要一个类型作为模板参数,而lambda表达式正是这样-一个表达式,即一个值,而不是一个类型,如果我在使用字符串键时没有指定哈希函数,这会给我带来很多错误。至于它是一个表达式,是的,我想这就是答案。相关:4.5.3对C++11的支持很少。不要把这个组合用于任何严重的事情。@MM.,比如:
std::无序映射m(1,hf)。第一个参数是初始桶计数,第二个参数是哈希器。遗憾的是,在这种情况下不能使用大括号初始化。有趣的是,虽然有点作弊,因为您不仅仅是将lambda函数作为模板参数传递。事实上,模板参数可以通过辅助模板函数一起避免,例如:
template auto make_unordered_map(size\t bucketCount,HASHER const&hf)->unordered_map{return unordered_map(bucketCount,hf);}
,如图所示。不过,这很有趣。:)
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’
auto hf = [](string const& key)->size_t { return key[0]; };

unordered_map<string const, int, decltype(hf)> m (1, hf);
                                 ^^^^^^^^^^^^        ^^
                                 passing type        object