gpt4 book ai didi

c++ - Reference_wrapper 不会在 cout 中打印,但 reference_wrapper 会吗?

转载 作者:行者123 更新时间:2023-12-02 03:32:47 27 4
gpt4 key购买 nike

为什么我尝试打印“string的reference_wrapper”的行会给出不支持的运算符<<“for“string的reference_wrapper”的错误,但不会给出“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 是一个函数模板,当传递 reference_wrapper 时,最后一个模板参数 Allocator无法推论;因为 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 是非模板,则不存在此类问题。

关于c++ - Reference_wrapper<string> 不会在 cout 中打印,但 reference_wrapper<int> 会吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60500741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com