I tried to overload the ostream << operator to print out a generic-typed variable, however main.cpp can not find the implementation. I am assuming that this is because the implementations exists in a .cpp file. I am aware that template functions must usually be defined in the header files, however this should not be the case for explicitly-instantiated functions. When I copy the implementation into my header file, it works just fine.
I'm thinking that I'm experiencing an issue that is unique to templated friend functions. Here are the relevant parts of my code.
I forward declared my Node class and the operator overload
template <typename T> class Node;
template <typename T> ostream& operator<< (ostream&, Node<T>&);
I declared the operator overload in my header file (Tree.h)
template <typename T>
class Node
{
...
friend ostream& operator<< <T> (ostream&, Node<T>&);
T data;
...
}
in my .cpp file, I implemented it
#include "Tree.h"
template <typename T>
ostream& operator<< (ostream& out, Node<T>& node)
{
out << node.data;
return out;
}
I explicitly instantiated my Node at the bottom of my Tree.cpp file
template class Node<int>;
then finally I called it from main.cpp
int main()
{
Node<int>* n0 = new Node<int>(0);
cout << (*n0);
}
and I get the following error:
undefined reference to 'std::ostream& operator<< <int> (std::ostream&, Node<int>&)'