问题
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&)'|
回答1:
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;
}
回答2:
Just define the friend function inside the class.
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)
{
out << "(" << v.coords[1] << " - " << v.coords[2] << ")";
return out;
}
};
template <unsigned short n>
Vector<n>::Vector()
{
coords.assign(n, 0.0);
}
int main()
{
Vector<3> toomas;
cout << toomas;
}
Tested: http://ideone.com/LDAR4
Or, declare the template function beforehand, using a forward prototype:
template <unsigned short n>
class Vector;
template <unsigned short n>
std::ostream& operator <<(std::ostream& out, const Vector<n>& v);
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;
}
Tested: http://ideone.com/8eTeq
来源:https://stackoverflow.com/questions/5284473/c-template-ostream-operator-question