The following code is giving me a compilation error. Can anyone please tell me why?
class mytype {
public:
int value;
mytype(int a) {
value = a;
}
friend ostream& operator<<(ostream& stream, const mytype& a) {
stream << a.value;//works
return stream;
}
friend ostringstream& operator<<(ostringstream& stream, const mytype& a) {
stream << (a.value);//compilation error
return stream;
}
};
Error:
error C2027: use of undefined type
‘std::basic_ostringstream<_Elem,_Traits,_Alloc>’
Upon fixing that:
error C2666: ‘operator <<‘ : 18 overloads have similar conversions
Final fix:
Declare constructor as explicit. Works on MSVC then.
I wonder why.
There is an overload ambiguity in the call to
operator<<in theostringstreamoverload.There are a number of
operator<<overloads that are members of theostreamclass, which is a base class ofostringstream. One of these is declared as:This overload is an exact match for the right-hand side (
a.valueis anint) but requires a derived-to-base conversion on the left-hand side (streamis anostringstream, which is derived fromostream).However, there is also your
ostringstreamoverload:This overload is an exact match for the left-hand side (
streamis anostringstream), and a user-defined converting constructor (yourmytype(int)constructor) can be used to converta.value(anint) to amytype.Since one overload matches the first argument better and the other overload matches the second argument better, there is an ambiguity. You can fix this either by:
ostream(using(ostream&)stream = a.value;), orexplicit.