Re: Implicit conversion to std::ostream
On 20 Jul., 23:31, Lars Storjord wrote:
Suppose we have the following class:
class ImplicitOstream {
public:
ImplicitOstream(std::ostream& strm) : strm(strm) {}
operator std::ostream&() { return strm; }
std::ostream& strm() { return strm; }
private:
std::ostream& strm;
};
Then the following won't work:
ImplicitStream implstrm;
implstrm << "Hello, world!\n";
Neither will operator<<(implstrm, cout);
However, the following does work:
void f(std::ostream& os)
{
os << "Hello\n";
}
f(implstrm);
Why won't the call to operator<<() succeed? Is it supposed to be like
this? I would assume that implicit type conversion wasn't invoked due
to the reference-to-non-const, but then it shouldn't have worked for f
() either, should it? Is there something I have overlooked?
Yes. The operator<< you want to call is a *member* of ostream. So, the
correct explicit syntax would be
ostream& myostream = implstrm;
myostream.operator<<("Hello World!");
If this operator<< had been a free non-template function it would have
worked like you wanted. But it even won't work for function templates:
template<typename T>
void bar(ostream& os, T const& x) {os << x;}
bar(implstrm,42);
because types have to "match exactly" (which includes lvalue
transformations and qualification adjustments)
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]