3

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
  • 8,226
  • 20
  • 73
  • 164
  • In a member function you conceptually have a hidden `this` as an extra parameter. Here the first argument to `operator<<` has to be `std::ostream&`, so it *could* possibly be a member of the stream class. As it is not, you have to make it a free function (non-member). – 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
  • 90,663
  • 31
  • 146
  • 203
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,458
  • 2
  • 12
  • 26
  • 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<<(std::ostream& os, const T& obj) { // write obj to stream return os; } ` – 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