idlebox / 2007 / 0301-StdOStreamPrintable.blog

C++ Code Snippet - Making a Custom Class ostream Outputable

Posted on 2007-03-01 14:47 by Timo at Permlink with Comments. Tags: std::string std::ostream printable c++ code-snippet

How to get a custom class to work with std::cout << obj; ? I for my part always forget the exact prototype of the required operator<<. Here is an minimal working example to copy code from:

#include <iostream>

struct myclass
{
    int a, b;

    myclass(int _a, int _b)
        : a(_a), b(_b)
    { }
};

// make myclass ostream outputtable
std::ostream& operator<< (std::ostream &stream, const myclass &obj)
{
    return stream << "(" << obj.a << "," << obj.b << ")";
}

int main()
{
    myclass obj(42, 46);

    std::cout << obj << std::endl;
}

Comment by bryane at 2007-04-27 17:49 UTC

it is perhaps better to make a pass-thru template to avoid most of the typing:


template <class BASECLASS>
class STREAMABLE : public BASECLASS
{
   friend std::ostream& operator<< (std::ostream &os, const STREAMABLE &obj) { return obj.emit(os); }
   virtual std::ostream& emit(std::ostream& os) const = 0;
};

With the template version, all you need to is:

struct myclass : public STREAMABLE
{
   std::ostream& emit(std::ostream& os) const { ... }
}

Post Comment
Name:
Homepage/Mail URI:

Many common HTML elements are allowed in the text, but no CSS style.
 
RSS 2.0 Weblog Feed Atom 1.0 Weblog Feed Valid XHTML 1.1 Valid CSS (2.1)