构造函数中的lambda实例化(lambda instantiation in constructor)

编程入门 行业动态 更新时间:2024-10-26 06:36:45
构造函数中的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>()’

我怎样才能克服这个问题?

I have such a 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); }

When I pass a lambda function for the hasher argument:

auto lambda = [](const std::pair<int, int>& x) { return pair_hash(x); };

I get the errors:

: 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

And:

error: use of deleted function ‘Correctness_Constructors_Test::TestBody()::<lambda(const std::pair<int, int>&)>::<lambda>()’

How can I overcome this problem?

最满意答案

这里的问题是你在构造函数成员初始化列表中默认构造my_hash_ (因为你没有提供),然后你在构造函数体中分配它。 由于my_hash_是一个lambda,因此它不是默认构造的,因为lambdas不是默认构造的。 您需要在成员初始化列表中初始化my_hash_ ,如

ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash()) : my_hash_(hasher) { //... }

The issue here is you default construct my_hash_ in your constructor member initialization list (because you do not provide one) and then you assign to it in the constructor body. Since my_hash_ is a lambda it is not default constructable as lambdas are not default constructable. You need to initialize my_hash_ in the member initializer list like

ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash()) : my_hash_(hasher) { //... }

更多推荐

本文发布于:2023-08-05 21:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439364.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   constructor   lambda   instantiation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!