Precursor
Precursor

Reputation: 642

C++ Format for cout << Automatically

If I had a simple class with two variables, x and y, and a function ToString() that returns a formatted string with the data. When I call

cout << simpleClass << "\n";

anyone know a way I could have simpleClass.ToString automatically called to return the correctly formatted string? I'm guessing there's a way to do this with operator functions, but I don't know how I would do this.

Upvotes: 5

Views: 535

Answers (2)

ildjarn
ildjarn

Reputation: 62985

If you're asking how to define such an operator,

template<class CharT, class TraitsT>
std::basic_ostream<CharT, TraitsT>&
operator <<(std::basic_ostream<CharT, TraitsT>& os, SimpleClass const& sc)
{
    return os << sc.ToString();
}

Upvotes: 9

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

You define

std::ostream& operator <<(std::ostream&, const SimpleClass&)

to call ToString(), passing the ostream&, and return the ostream&.

Upvotes: 2

Related Questions