I want to derive a stringstream so that I can use the operator<< to construct a message which will then be thrown. The API would look like:
error("some text") << " more text " << 42 << std::endl;
This should do a
throw "some text more text 42"
So what I did is make an errorbuf (inheriting from streambuf) which overloads the 'overflow' method and then create an ostream(&errorbuf). I wonder if I shouldn't instead inherit from basic_ostringstream or something...
I'll trot out my favourite macro again here:
#define ATHROW( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw ALib::Exception( os.str(), __LINE__, __FILE__ ); \
} \
In use:
ATHROW( "Invalid value: " << x << " should be " << 42 );
the exception type is from my own library, but I think you get the idea. This is much simpler than deriving your own stream class, and avoids lots of nasty complications with op<<().