friends and templates

Hi,
I want to put a friend function declaration into .cpp file and keep only its prototype in .h but I keep getting this linker error

undefined reference to `std::basic_ostream<char, std::char_traits<char> >& Lattice::operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, Lattice::Simple<int> const&)'
collect2: ld returned 1 exit status

here is my .h file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <sstream>

template<typename T>
class Simple;

template<typename T>
std::ostream& operator <<(std::ostream& os, const Simple<T>& obj);

template<typename T>
class Simple
{
public:
/*...*/
	friend std::ostream& operator<<<> (std::ostream& os, const Simple<T>& obj);
private:
	int _x, _y, _z;
	T *_matrix;
};


and .cpp file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "Simple.h"
template<typename T>
std::ostream& operator<<(std::ostream& os, const Simple<T>& obj)
{
	os << '[' << obj._x << ']';
	for (int i = 0; i < obj._x; ++i)
	{
		if (i == 0)
			os << '(' << obj._matrix[i];
		else
			os << ',' << obj._matrix[i];
	}
	os << ')';
	return os;
}

template class Simple<int>;
template class Simple<double>;


and this is main()
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "Simple.h"

int main()
{
	Simple<int> aaa;
	std::cout << aaa;
	return 0;
}


Please help
Last edited on
You need to explicit instantiate the functions too.
1
2
template std::ostream& operator<<(std::ostream& os, const Simple<int>& obj);
template std::ostream& operator<<(std::ostream& os, const Simple<double>& obj);


And guard your headers http://www.cplusplus.com/forum/articles/10627/
Last edited on
Topic archived. No new replies allowed.