3

我正在试验std::reference_wrapper. 我不明白为什么以下内容适用于 astd::vector但不适用于 a std::unordered_map

#include <functional>
#include <vector>
#include <unordered_map>

using namespace std;

int main()
{
  vector<vector<long>> x;

  vector<reference_wrapper<vector<vector<long>>>> y;
  y.push_back(ref(x)); // OK

  unordered_map<string, reference_wrapper<vector<vector<long>>>> m;
  m["lol"] = ref(x); // NOT OK
}

这是我得到的编译错误

/usr/include/c++/7.2.0/tuple:1652:70: error: no matching function for call to ‘std::
reference_wrapper<std::vector<std::vector<long int> > >::reference_wrapper()’       
         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
                                                                      ^
In file included from /usr/include/c++/7.2.0/bits/std_function.h:44:0,              
                 from /usr/include/c++/7.2.0/functional:58,                         
                 from test.cpp:1:         
/usr/include/c++/7.2.0/bits/refwrap.h:325:7: note: candidate: constexpr std::referen
ce_wrapper<_Tp>::reference_wrapper(const std::reference_wrapper<_Tp>&) [with _Tp = s
td::vector<std::vector<long int> >]       
       reference_wrapper(const reference_wrapper&) = default;                       
       ^~~~~~~~~~~~~~~~~
/usr/include/c++/7.2.0/bits/refwrap.h:325:7: note:   candidate expects 1 argument, 0
 provided            
/usr/include/c++/7.2.0/bits/refwrap.h:319:7: note: candidate: std::reference_wrapper
<_Tp>::reference_wrapper(_Tp&) [with _Tp = std::vector<std::vector<long int> >]     
       reference_wrapper(_Tp& __indata) noexcept                                    
       ^~~~~~~~~~~~~~~~~
/usr/include/c++/7.2.0/bits/refwrap.h:319:7: note:   candidate expects 1 argument, 0
 provided  

有人可以解释我做错了什么吗?

4

1 回答 1

7

m["lol"]使用无序映射operator[]。该运算符返回对地图中项目的引用。如果没有这样的项目,这是有问题的。

为了解决这个问题,它将默认构造它应该返回的项目。这就是问题所在,因为std::reference_wrapper它不是默认可构造的。

为了使这两个示例更加等效,您需要使用std::unordered_map::insertor std::unordered_map::emplace

于 2017-10-06T22:58:23.630 回答