Passing unknown classes to String Streams in C++

c++, sstream, stream

Solution

It sounds to me like you want to make stream insertion operators. for a class you want to be able to output to a stream, define the free function:

std::ostream& operator<<(std::ostream& stream, const SomeClassType& x)
{
    stream << x.someData();

    return stream;
}

So if we have `SomeClassType z;`, and we do `std::cout << z` (or any other output stream, like an `fstream` or `stringstream`), the compiler will look for and find our function, and call it. That is, `std::cout << z` becomes `operator<<(std::cout, z)` and inside there you output what you need.

Problem

I am using a template function and I am passing and I may be sending instances of a variety of classes to a string stream. What can I do to make sure this continues to work? Let me be more specific where do I define the behavior for this? Is there some member that should be on each class being sent to the string stream, should I in some enhance or extend the existing String stream (I was thinking building a class that inherits from sstream and overloads the << operator to handle all the possible classes)? I had trouble even finding documentation on this, so even links to more resources would be helpful.

Original source