2

I would like to overload the << operator, to print out a class instance to the console like this:

std::cout << instance << std::endl;

I've found a solution here: https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

But I cannot use it, because my class is templated:

template<typename T>
myClass {
    //code...
};

Edit: I get an error, if I try to define it inside the class body: it must take only one argument

Iter Ator
  • 7,047
  • 16
  • 57
  • 138
  • In a member function you conceptually have a hidden `this` as an extra parameter. Here the first argument to `operator< – Bo Persson Jan 15 '16 at 20:16

2 Answers2

3

Sure you can use the example, just adapt it for your template.

Instead of

ostream& operator<<(ostream& os, const Date& dt)

you would need

template<class T>
ostream& operator<<(ostream& os, const myClass<T>& dt)
Bo Persson
  • 88,437
  • 31
  • 141
  • 199
1

You can try this (adapt it to your code):

std::ostream& operator<<(std::ostream& os, const T& obj)
{
    // write obj to stream
    return os;
}
Paulo
  • 1,241
  • 2
  • 9
  • 25
  • I get an error, if I try to define it inside the class body: `it must take only one argument` – Iter Ator Jan 15 '16 at 13:19
  • You can put it outside the class definition. Try and let me know if it works. Something like: `template myClass { //code... }; std::ostream& operator< – Paulo Jan 15 '16 at 13:20
  • Yes, it works if I change the name of the template parameters – Iter Ator Jan 15 '16 at 13:24