0

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

Jonas
  • 2,974
  • 4
  • 24
  • 23
  • Also you can lookup here. http://stackoverflow.com/questions/10787655/c-friend-declaration-declares-a-non-template-function – Arunmu Nov 03 '13 at 13:53

1 Answers1

1

You need the template argument for the prototype:

template <typename T>
friend ostream& operator<<(ostream& os, const Vect<T>& v);
David G
  • 94,763
  • 41
  • 167
  • 253
  • Your proposal took me one step further! Thanks! Now, the compiler complains about accessing the protected member variables v1_, v2_ and v3_ within the operators (<<, *). Can't friend operators access protected class members? – Jonas Nov 03 '13 at 13:59
  • @Jonas I think you need the same solution for `operator*`. And yes, friend functions can access protected class members. – David G Nov 03 '13 at 14:04
  • Change the declaration inside the class to `template friend ostream& operator<<(ostream& os, const Vect& v);`. As it is now, the declaration inside the class does not declare the `operator>>` that is defined later. – jrok Nov 03 '13 at 14:05
  • I already added the template argument to both prototypes. Nevertheless, the compiler now complains about accessing the protected member variables within both operators (<< and *): – Jonas Nov 03 '13 at 14:06
  • Do as I said in my previous comment. That goes for both of you, Jonas and Hex guy :P – jrok Nov 03 '13 at 14:07
  • Thanks jrok, it worked! Of course also thanks for your help 0x499602D2! – Jonas Nov 03 '13 at 14:09