如何重载<<具有非类型参数的类模板的运算符?

时间:2012-12-18 11:36:10

标签: c++

我正在尝试重载类模板的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>&);

2 个答案:

答案 0 :(得分: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&);
    ...

答案 1 :(得分:5)

良好的做法是让一些公共职能printContent像这样 -

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

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

因此您不需要任何friend s