2

考虑以下代码:

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_convertibletrait 的地方破坏我的一些代码。

这种设计是否有任何理由涉及不存在通用复制构造函数:

template <typename Y>
reference_wrapper<T>::reference_wrapper(const reference_wrapper<Y>&)

(就像在std::shared_ptr例如)将允许这样的隐式转换?

4

1 回答 1

0

与其基础类型之间没有隐式的自动转换std::reference_wrapper(因为它可能不安全且令人困惑)。

正确的语法应该是:

std::reference_wrapper<const int> z = x.get();
于 2013-09-11T12:13:56.690 回答