Can't overload ostream insert operator for template class?

I have a list class that I wanted to be able to output using <<, but it always gives me an error. I tried doing something simpler for a test and got the same error. Using VS I got this error
main.obj : error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class MyClass<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$MyClass@H@@@Z) referenced in function _main

Is there some way to do what I'm trying? Here's what I have for my test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
template <typename T>
class MyClass {
public:
	T t;
	friend ostream& operator<<(ostream&, MyClass&);
};
template <typename T>
ostream& operator<<(ostream& out, MyClass<T>& myObject) {
	return out << myObject.t;
}
int main() {
	MyClass<int> myObject;
	myObject.t = 5;
	cout << myObject;
}
Try adding the template stuff to the friend declaration
1
2
3
4
5
6
7
template <typename T>
class MyClass {
public:
	T t;
        template < typename Type >
          friend ostream& operator<<(ostream&, MyClass<Type>&);
};
Last edited on
Also, as a matter of good practice, operator<< should take MyClass by const reference.
Topic archived. No new replies allowed.