reference_wrapper<string> 不在 cout 中打印,但 reference_wrapper<int> 打印?

reference_wrapper<string> does not print in cout, but reference_wrapper<int> does?

为什么我尝试打印 "reference_wrapper for string" 的那一行对于 "reference_wrapper for string" 不支持的运算符 << 给出错误,但在 "reference_wrapper for int" 上却没有给出错误?

int main(){

    int  s= 43;
    string str = "hello";

    reference_wrapper<int> x{s};
    reference_wrapper<string> y{str};

    x.get() = 47;
    y.get() = "there";

    cout<<"printing original int "<<s<<"\n";
    cout<<"printing original string "<<str<<"\n";

    cout<<"printing reference_wrapper for int "<<x<<"\n";
    cout<<"printing reference_wrapper for string "<<y<<"\n"; // gives error

    int& refint = x;
    string& refstr = y;

    cout<<"printing reference for int "<<refint<<"\n";
    cout<<"printing reference for string "<<refstr<<"\n";
}

operator<< for std::string is a function template, when being passed a reference_wrapper, the last template argument Allocator fails to be deduced; because implicit conversion won't be considered in template argument deduction.

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

作为解决方法,您可以显式调用 std::reference_wrapper<T>::get 或执行显式转换。

另一方面,operator<< for int是非模板,则没有这样的问题。