C++ 引用包装器与隐式转换

C++ 引用包装器与隐式转换,c++,c++11,C++,C++11,考虑到以下准则: int v = 12; std::reference_wrapper<int> x(v); std::reference_wrapper<const int> y(x); // (1) This works std::reference_wrapper<const int> z = x; // (2) This fails 就像在std::shared_ptr中那样,它允许这样的隐式转换?在std::reference_包装器和它的基础类

考虑到以下准则:

int v = 12;
std::reference_wrapper<int> x(v);
std::reference_wrapper<const int> y(x);  // (1) This works
std::reference_wrapper<const int> z = x; // (2) This fails

就像在std::shared_ptr中那样,它允许这样的隐式转换?

在std::reference_包装器和它的基础类型之间没有隐式的自动转换,因为它可能是不安全的和令人困惑的

正确的语法应为:

std::reference_wrapper<const int> z = x.get();

不管出于什么原因,如果您需要引用包装,您应该始终打开它们。@Xeo这是完全相反的,我正在将一个UnaryFunction的引用包装作为一个需要一个UnaryFunction的模板类的参数传递。更确切地说,TyPulfBoosi::TraveStAlpuliTyror TyPulfBoosi::TraveSyter迭代器SistaIsActer,我希望迭代器可以被隐式转换为CistaTyrActucor。在C++中,同一个基类型的不同的专门化是无关的,而不管实例化类型的关系如何。std::reference_包装器与std::reference_包装器的关系并不比与std::reference_包装器的关系更密切。虽然您可能希望它们是可转换的,但我不会说您应该期望它是可转换的。@Xeo:我们是否需要它在表达式std::reference_wrapper z=x;中的某个位置;?
template <typename Y>
reference_wrapper<T>::reference_wrapper(const reference_wrapper<Y>&)
std::reference_wrapper<const int> z = x.get();