I tested it.
I can guess that operator<< cannot bind a temporary to a non-constant reference, so any externally defined operator <<functions will not work on a temporary Foo, but any members of the class will do so if ostream or ostringstream have any internal members of operator<< which they will work.
Therefore, it may be that overloading the pointer is a member function, while special for const char * is externally declared.
A non-temporary can be associated with a non-constant reference for a more specialized overload.
If you really need it, you can bypass the shell
class Foo : { mutable std::ostringstream oss; public: ~Foo() { std::cout << oss.str(); } template<typename T> std::ostream& operator<<( const T& t ) const { return oss << t; } };
Tested and working. The first operator <will return the base stream to you.
I tried this too, but this has been fixed:
class Foo : std::ostringstream { Foo & nonconstref; public: Foo() : nonconstref( *this ) {} ~Foo() { std::cout << str(); } template<typename T> std::ostream& operator<<( const T& t ) const { return nonconstref << t; } };
This also works:
class Foo : public std::ostringstream { public: Foo() {} ~Foo() { std::cout << str(); } Foo& ncref() { return *this; } }; int main() { Foo foo; foo << "Test1" << std::endl; Foo().ncref() << "Test2" << std::endl; }
Cashcow
source share