How to use friend operators in a template class? [

2019-09-06 17:39发布

问题:

This question already has an answer here:

  • Overloading << operator in C++ when using templates in linked list program 1 answer

I have template class which has some friend operators. The compiler complains about "friend declaration declares a non-template function". Unfortunately, I don't know how to resolve this error. Any hints?

The code looks as follows:

template<typename X> class Vect
{

protected:
    X v1_;
    X v2_;
    X v3_;

public:
    Vect( X v1, X v2, X v3 );
    Vect( const Vect<X> &v);
    ~Vect();
    void printVect( );
    friend ostream& operator<<(ostream& os, const Vect<X>& v);
    friend const Vect<X> operator*(Vect<X>& v, X n);
    friend const Vect<X> operator*(X n, Vect<X>& v);


};


template<typename X> Vect<X>::Vect( X v1, X v2, X v3 )
    : v1_(v1),v2_(v2), v3_(v3)  
{
//  v1_ = v1;
//  v2_ = v2;
//  v3_ = v3;  
}

template<typename X> Vect<X>::Vect( const Vect<X> &v )
    : v1_(v.v1_), v2_(v.v2_), v3_(v.v3_)
{
}

template<typename X> Vect<X>::~Vect( )
{
} 

template<typename X> void Vect<X>::printVect( )
{
    cout << "(" << v1_ << ", " << v2_ << ", " << v3_ << ")" << endl; 
}

template<typename X> ostream& operator<<(ostream& os, const Vect<X>& v)
{
    os << "(" << v.v1_ << ", " << v.v2_ << ", " << v.v3_ << ")" << endl;
    return os;
}

template<typename X> const Vect<X> operator*(Vect<X>& v, X n)
{
    Vect<X> tmp(v);
    tmp.v1_ *= n;
    tmp.v2_ *= n;
    tmp.v3_ *= n;
    return tmp;
}

template<typename X> const Vect<X> operator*(X n, Vect<X>& v)
{
    return v*n;
}

Thans in advance,

Jonas

回答1:

You need the template argument for the prototype:

template <typename T>
friend ostream& operator<<(ostream& os, const Vect<T>& v);