Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

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";
}
like image 548
Gtrex Avatar asked Aug 22 '26 23:08

Gtrex


1 Answers

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.

As the workaround, you can call std::reference_wrapper<T>::get explicitly or perform explicit conversion.

On the other hand, operator<< for int is a non-template, then doesn't have such issue.

like image 97
songyuanyao Avatar answered Aug 24 '26 14:08

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!