Lambda构造函数中的实例化
lambda instantiation in constructor
我有这样的构造函数:
ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash())
{
this->my_hash_ = hasher;
if (expected_size != kUndefinedSize)
table.reserve(expected_size);
}
当我通过 hasher
参数的lambda函数时:
auto lambda = [](const std::pair<int, int>& x) {
return pair_hash(x);
};
我得到错误:
: In instantiation of ‘ConcurrentHashMap<K, V, Hash>::ConcurrentHashMap(int, int, const Hash&) [with K = std::pair<int, int>; V = std::__cxx11::basic_string<char>; Hash = Correctness_Constructors_Test::TestBody()::<lambda(const std::pair<int, int>&)>]’:
required from here
和:
error: use of deleted function ‘Correctness_Constructors_Test::TestBody()::<lambda(const std::pair<int, int>&)>::<lambda>()’
如何克服这个问题?
这里的问题是您在构造函数成员初始化列表中默认构造 my_hash_
(因为您不提供一个),然后在构造函数正文中分配给它。由于my_hash_
是lambda,因此无法构造默认值,因为lambdas无法构造。您需要在成员初始化列表中初始化my_hash_
,例如
ConcurrentHashMap(int expected_size, int expected_threads_count,
const Hash& hasher = Hash()) : my_hash_(hasher)
{
//...
}
相关文章:
- 为什么std::vector和std::valarray初始化构造函数不同
- 我应该在C++中将这些结构用作参数化构造函数吗?
- 将显式实例化的函数模板与转换匹配
- 为什么即使我调用参数化构造函数也会调用默认构造函数?
- 使用向量初始化参数化构造函数的对象数组
- 初始化构造函数C++中结构的向量
- 我们可以用参数化构造函数初始化结构的数组吗?
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 如何同时别名和实例化模板函数?
- 如何在其他类中使用参数化构造函数制作类的对象?
- C++ 中常量属性的初始化构造函数错误
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- 如何执行参数化构造函数的调用?
- 为什么我不能在类中使用参数化构造函数?
- 如何在 QML 中实例化C++组件 - WITH 参数化构造函数
- C++如何用参数化构造函数实例化对象
- 基于运行时类型实例化构造函数
- 模板类的模板化构造函数的显式实例化
- 类模板的显式实例化没有实例化构造函数
- 初始化实例的构造函数内的静态成员