Sunday, May 17, 2009

Making a C++ object printable to standard output

You want to make a C++ object printable to the standard output. For example you have an object call ScoredSequence and you want do be able to do: ScoredSequence s("BLAHBLAH"); cout << s; You need to add a << operator to ScoredSequence, for example:

class ScoredSequence {
public:

ScoredSequence(string s) : sequence(s) {
}


string get_sequence() {
return s;
}

/// \brief Extractor which prints the whole sequence.
inline friend std::ostream& operator<<(std::ostream& out, const ScoredSequence& s) {
out << s.get_sequence();
return out;
}

private:
string sequence;
};

2 comments:

nobodycares said...

Couldn't you add some more arguments there so that you can selectively print out different things. Like if you didn't want the sequence, but the id of the read to be printed out. I suppose you could always recompile with s.getID(); but that seems like a pain.

Or a debug flag, with more infos.

new said...

so the point here is I want to have a default output operator for a class. So if i'm doing some debugging, or reporting I can just do:

cout << m_object << endl;

and it'll dump something sensible. No idea how you'd get it to take arguments becaause the << operator doesn't take arguments. You could of course do something like cout << m_object.get_string() << endl; But for this application that defeats the purpose, I want to be able to use the default output operator so the same code will work for say, an int, a string, or my own object.