Another C++ tip

Someone asked a question on #kde-devel the other day, wondering what the best way to do a stream insertion operator was. Their first suggestion was to do something like the following:

<b>class</b> Foo {<br /> ostream &<b>operator</b><br /> };<br />

The major problem is that it wouldn’t compile that way. Even if it did, you wouldn’t be able to string insertions together like you can with cout or kdDebug().

There are two well-known ways of fixing this, both of which involve non-member functions:

  • The first way is typically to make the operator
    • The other way is described in a book I read, and it also involves an external function, although it doesn’t need to be a friend.</ul> Basically a class defines a virtual public method called print which accepts an output stream (e.g. ostream, QDataStream, etc) and is responsible for inserting itself onto that stream. Then the external stream simply calls the print() method and immediately returns the stream. Example:

    `class Foo {
    public:
    virtual void print(ostream &o) const {
        /* output onto o */
    }
    };</p>

ostream &operator
    x.print(o);
    return o;
}` So there you go, my monthly C++ tidbit. :-)