Search code examples
c++templatesfriend

vect.hpp:13:33: error: declaration of ‘operator<<’ as non-function


I have this error

vect.hpp:13:33: error: declaration of ‘operator<<’ as non-function

for the code :

#include <iostream>

template<unsigned d>
class Vect{
    protected:
        double * coord;
    public:
        Vect() {for(int i=0, i<d, i++){*(coord+i)=0;}}
        ~Vect(){delete coord; coord=nullptr;}
        Vect(const Vect &);
        double operator=(const Vect &);
        double operator[](unsigned i) const{return *(coord+i);}
        friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 
};

for the line :

friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 

Solution

  • The friend declaration refers to the instantiation of the operator<< but there's no primary template declaration. You need to declare the operator template in advance. e.g.

    // forward declaration
    template<unsigned d>
    class Vect;
    
    // primary template declaration of operator<<
    template<unsigned d>
    std::ostream & operator<< (std::ostream &, const Vect<d> &); 
    
    template<unsigned d>
    class Vect{
        protected:
            double * coord;
        public:
            Vect() {for(int i=0; i<d; i++){*(coord+i)=0;}}
            ~Vect(){delete coord; coord=nullptr;}
            Vect(const Vect &);
            double operator=(const Vect &);
            double operator[](unsigned i) const{return *(coord+i);}
            friend std::ostream & operator<< <>(std::ostream &, const Vect<d> &); 
    };
    

    LIVE