Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Format for cout << Automatically

Tags:

c++

cout

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.

like image 644
Precursor Avatar asked Jul 21 '11 01:07

Precursor


1 Answers

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();
}
like image 59
ildjarn Avatar answered Sep 27 '22 22:09

ildjarn