tags:

views:

181

answers:

1

Consider the following snippet:

struct ObjectInterface
{
    virtual ~ObjectInterface() {}
    virtual void Print(std::ostream& target) const = 0;
};

struct Foo : ObjectInterface
{
    virtual void Print(std::ostream& target) const
    {
        target << "Foo";
    }
};

struct Bar : ObjectInterface
{
    virtual void Print(std::ostream& target) const
    {
        target << "Bar";
    }
};

Is there any way to change Print in ObjectInterface to the standard "std::ostream& operator<<"-type of output? I can't make it work.

EDIT: I'm basically trying to figure out if I can make friend work with virtual.

+5  A: 

You need a free function:

ostream & operator << ( ostream & os, const ObjectInterface & oi ) {
    oi.Print( os );
    return os;
}
anon
God, that's terribly simple. I can't believe I didn't think of that... Thanks.
Don't feel too bad. The first guy at Bell Labs (I guess) that thought of it was probably pretty pleased with himself - the rest of us just use it.
anon