panthema / 2007 / 0301-StdOStreamPrintable

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

Posted on 2007-03-01 14:47 by Timo Bingmann at Permlink with 1 Comments. Tags: #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>
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
E-Mail or Homepage:

URLs (http://...) are displayed, e-mails are hidden and used for Gravatar.

Many common HTML elements are allowed in the text, but no CSS style.