C++ 如何在我的(模板化)类中使用std::cout?

C++ 如何在我的(模板化)类中使用std::cout?,c++,templates,C++,Templates,我想重载您可以尝试以下方法(使其适应您的代码): std::ostream&operator确保您可以使用该示例,只需根据您的模板调整它即可 而不是 ostream& operator<<(ostream& os, const Date& dt) ostream&operator如果我试图在类主体内部定义它,就会得到一个错误:它只能接受一个参数您可以将它放在类定义之外。试着让我知道它是否有效。类似于:template myClass{//code…};std

我想重载
您可以尝试以下方法(使其适应您的代码):


std::ostream&operator确保您可以使用该示例,只需根据您的模板调整它即可

而不是

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

ostream&operator如果我试图在类主体内部定义它,就会得到一个错误:
它只能接受一个参数
您可以将它放在类定义之外。试着让我知道它是否有效。类似于:
template myClass{//code…};std::ostream&operatorYes,如果我更改成员函数中模板参数的名称,它会起作用。在概念上,您可以将隐藏的
this
作为额外参数。这里是
运算符的第一个参数
template<typename T>
myClass {
    //code...
};
std::ostream& operator<<(std::ostream& os, const T& obj)
{
    // write obj to stream
    return os;
}
ostream& operator<<(ostream& os, const Date& dt)
template<class T>
ostream& operator<<(ostream& os, const myClass<T>& dt)