如何将 std::cout 与我的(模板化)类一起使用

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

本文关键字:一起 std cout 我的      更新时间:2023-10-16

我想重载<<运算符,将类实例打印到控制台,如下所示:

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

我在这里找到了一个解决方案:https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

但我不能使用它,因为我的类是模板化的:

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

编辑:如果我尝试在类体内定义它,我会收到一个错误:it must take only one argument

当然,您可以使用该示例,只需针对您的模板对其进行调整即可。

而不是

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

你需要

template<class T>
ostream& operator<<(ostream& os, const myClass<T>& dt)

你可以试试这个(适应你的代码):

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