C++ template/ostream operator question

Jaanus picture Jaanus · Mar 12, 2011 · Viewed 19.9k times · Source

trying to get the operator to work, but throwing me bunch of errors:

my header file

template <unsigned short n>
class Vector {
public:
    std::vector<float> coords;

    Vector();
    Vector(std::vector<float> crds);
    friend std::ostream& operator <<(std::ostream& out, const Vector& v);
};

template <unsigned short n>
Vector<n>::Vector() {
coords.assign(n, 0.0);
}

template <unsigned short n>
std::ostream& operator<<(std::ostream& out, const Vector<n>& v) {
out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
return out;
}

test file

#include <iostream>
#include "vector.h"
using namespace std;

int main() {
Vector<3> toomas;
cout << toomas;

}

error:

C:\CodeBlocks\kool\praks3\vector.h|14|warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Vector&)' declares a non-template function|

C:\CodeBlocks\kool\praks3\vector.h|14|note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) |

obj\Debug\test.o||In function `main':|

C:\CodeBlocks\kool\praks3\test.cpp|8|undefined reference to `operator<<(std::ostream&, Vector<(unsigned short)3> const&)'|

Answer

Nawaz picture Nawaz · Mar 12, 2011

Please look at the error, it says,

friend declaration 'std::ostream& operator<<(std::ostream&, const Vector&)' declares a non-template function|

That means you need to make the operator<< a template function.

So in the class, you've to declare it as:

template<unsigned short m> //<----note this: i.e make it template!
friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);

Then define it as,

template <unsigned short m>
std::ostream& operator<<(std::ostream& out, const Vector<m>& v) {
   out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
   return out;
}