简体   繁体   English

引用包装器<string>不在 cout 中打印,而是在 reference_wrapper 中打印<int>做?

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

Why the line where i am trying to print the "reference_wrapper for string" is giving error for unsupported operator<< for "reference_wrapper for string" but does not give on "reference_wrapper for int"?为什么我试图打印“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; operator<< for std::string是一个函数模板,当传递一个reference_wrapper ,最后一个模板参数Allocator无法推导出; 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.类型推导不考虑隐式转换(上面列出的类型调整除外):这是 重载解析的工作,稍后会发生。

As the workaround, you can call std::reference_wrapper<T>::get explicitly or perform explicit conversion.作为解决方法,您可以显式调用std::reference_wrapper<T>::get或执行显式转换。

On the other hand, operator<< for int is a non-template, then doesn't have such issue.另一方面, 对于int operator<<是非模板,则没有这样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM