Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I'm trying to overload operator<< of a class template , like this:

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;
}

the code above is running corrent!but i want to know if there is any way to overload operator<< in a way by not setting it as a function template:

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

like image 664
std Avatar asked Dec 18 '12 11:12

std


2 Answers

Yes, but you have to predeclare the template and use <> syntax:

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&);
    ...
like image 162
ecatmur Avatar answered Sep 19 '22 22:09

ecatmur


Good practice is to have some public function printContent like this -

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

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

thus you don't need any friends

like image 31
triclosan Avatar answered Sep 20 '22 22:09

triclosan