【问题标题】:std::ref implicit conversion to reference confusionstd::ref 隐式转换为引用混淆
【发布时间】:2020-07-25 20:10:31
【问题描述】:

我知道一个 std::ref(object) 创建一个 std::reference_wrapper(object),并且 std::reference_wrapper 有一个非显式类型转换运算符成员函数

operator T&() const

我知道当模板参数推导发挥作用时,这会影响我使用它的方式: 所以在下面的打印中,如果我用 std::ref("hello") 调用它,参数的类型 T 被推断为 std::reference_wrapper

template <class T>
void Print(T t)
{
    std::cout << t << std::end;
}

为什么这行不编译?

std::string s = "hello";
std::cout << std::reference_wrapper<std::string>(s) << std::endl;

实例化的特化应该有一个

operator std::string&() const

类型转换函数,为什么我不能像这样使用引用包装器呢?

【问题讨论】:

    标签: c++ type-conversion implicit-conversion ref reference-wrapper


    【解决方案1】:

    您尝试使用的operator&lt;&lt; 重载具有以下形式(来自cppreference.com):

    template <class CharT, class Traits, class Allocator>
    
    std::basic_ostream<CharT, Traits>&
        operator<<(std::basic_ostream<CharT, Traits>& os,
                   const std::basic_string<CharT, Traits, Allocator>& str);
    

    第二个函数参数包含模板参数,不是非推导上下文。因此它必须推导出模板参数。模板参数推导不考虑隐式转换,因为std::reference_wrapper 不是std::basic_string,推导将失败。 std::reference_wrapper 是否可以转换为 std::string(或对其中的引用)无关紧要。

    澄清一下,std::stringstd::basic_string 的专业化 std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt;&gt; 的别名。 std::basic_string 可以专门用于任何字符类型,例如wchar_t(别名为std::wstring)。其他专业根本不常用。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2016-12-03
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多