1

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> &); 
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Hitan Elo
  • 63
  • 1
  • 10

2 Answers2

1

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

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

You can also do do the definition inside the class.

#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 &os, const Vect<d> &obj)
        {
          // Your code goes here
        }

};
Imanpal Singh
  • 1,105
  • 1
  • 12
  • 22