3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.