考虑以下代码:
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
如果我理解正确,(1) 有效,因为它只需要一个用户转换,(2) 失败,因为它在转换序列中涉及两个用户转换:
std::reference_wrapper<int>::operator int& and
std::reference_wrapper<const int>::(const int&)
因此,std::reference_wrapper<int>
不能隐式转换到std::reference_wrapper<const int>
这破坏了我使用 std::is_convertible
的一些代码特质。
这种设计是否涉及不存在通用复制构造函数的任何原因:
template <typename Y>
reference_wrapper<T>::reference_wrapper(const reference_wrapper<Y>&)
(就像在 std::shared_ptr
中一样)允许这样的隐式转换?
std::reference_wrapper
与其基础类型之间没有隐式自动转换(因为它可能不安全且容易混淆)。
正确的语法应该是:
std::reference_wrapper<const int> z = x.get();
我是一名优秀的程序员,十分优秀!