How to make a C++ class compatible with stringstream objects?
<p>I would like to be able to serialize my C++ classes using standard techniques like std::stringstream or boost::lexical_cast.</p>

<p>For example if I have a Point object (2, 4) then I would like to serialize it to "(2, 4)", and also be able to construct a Point object from this string.</p>

<p>I have some code already but with a few issues. Point to string works, but sometimes the input isn't completely read from the stream. The string to Point conversion results in a bad_cast exception.</p>

<pre><code>class Point
{
public:
    Point() : mX(0), mY(0) {}
    Point(int x, int y) : mX(x), mY(y){}
    int x() const { return mX; }
    int y() const { return mY; }
private:
    int mX, mY;
};

std::istream&amp; operator&gt;&gt;(std::istream&amp; str, Point &amp; outPoint)
{
    std::string text;
    str &gt;&gt; text; // doesn't always read the entire text
    int x(0), y(0);
    sscanf(text.c_str(), "(%d, %d)", &amp;x, &amp;y);
    outPoint = Point(x, y);
    return str;
}

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, const Point &amp; inPoint)
{
    str &lt;&lt; "(" &lt;&lt; inPoint.x() &lt;&lt; ", " &lt;&lt; inPoint.y() &lt;&lt; ")";
    return str;
}

int main()
{   
    Point p(12, 14);    
    std::string ps = boost::lexical_cast&lt;std::string&gt;(p); // "(12, 14)" =&gt; OK    
    Point p2 = boost::lexical_cast&lt;Point&gt;(ps); // throws bad_cast exception!
    return 0;
}
</code></pre>

<p>How can I fix these problems?</p>
