c++templatesreference-wrapper

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";
}

Solution

  • 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.