Wednesday, October 6, 2010

A hacky way to get your class streaming out

Needing a quick way to seem to contents of a classes.. dump it into cout with a overloaded operator<< and an existing print function of some kind with very little fuss..

//complie with g++
#include <iostream>
#include <sstream>

using namespace std;

class A  {
public:
    A(): str1("Hi"), str2("There") {}
 
    string print()
    {
 ostringstream out;
 out << " str1: " << str1 << endl;
 out << " str2: " << str2 << endl;
 return out.str();
    }

private:
    string str1;
    string str2;
};

ostream& operator<<(ostream& out, A& val)
{
    out << val.print();
    return out;
}

int main()
{
    A test;
    cout << test << endl;
    return 0;
}

No comments:

Post a Comment