簡體   English   中英

如何使用非類型參數重載<<類模板的運算符?

[英]how to overload << operator of class template with non-type parameter?

我正在嘗試重載類模板的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>&);

是的,但您必須預先聲明模板並使用<>語法:

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&);
    ...

好的做法是有一些像這樣的公共功能printContent -

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

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

因此你不需要任何friend

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM