6

我正在尝试重载operator<<类模板,如下所示:

template<int V1,int V2>
class Screen
{
    template<int T1,int T2> friend ostream& operator<< (ostream &,Screen<T1,T2>&);  
    private:
        int width;  
        int length;
    public:
        Screen():width(V1),length(V2){}
};
template<int T1,int T2>
ostream& operator<< (ostream &os,Screen<T1,T2> &screen)
{
    os << screen.width << ' ' << screen.length;
    return os;
}

上面的代码运行正确!但我想知道是否有任何方法可以operator<<通过不将其设置为函数模板来以某种方式重载:

friend ostream& operator<< (ostream &,Screen<T1,T2>&); ?

4

2 回答 2

6

是的,但您必须预先声明模板并使用<>语法:

template<int V1, int V2> class Screen;
template<int T1, int T2> ostream &operator<< (ostream &,Screen<T1,T2> &);
template<int V1, int V2>
class Screen
{
    friend ostream& operator<< <>(ostream &, Screen&);
    ...
于 2012-12-18T11:41:09.410 回答
5

好的做法是有一些printContent像这样的公共功能 -

void Screen::printContent(ostream &os)
{
    os << width << ' ' << length;
}

ostream& operator<< (ostream &os,Screen<T1,T2> &screen)
{
    screen.printContent(os);
    return os;
}

因此你不需要任何friends

于 2012-12-18T11:44:50.053 回答