简体   繁体   中英

How to use std::cout with my (templated) class?

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

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)

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

std::ostream& operator<<(std::ostream& os, const T& obj)
{
    // write obj to stream
    return os;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM