Typically for my templated classes, I include declarations in a .hpp
file and templated implementation code in a .t.hpp
file. I explicitly instantiate the class in a .cpp
file:
template class MyClass< AnotherClass >;
whose object code gets put in a library.
The problem is that if I try to print the object with operator<<
, which is declared in the .hpp
file and defined in the .t.hpp
file as:
template<class T>
std::ostream& operator<<( std::ostream& os, const MyClass<T>& c)
{
os << "Hello, I am being output.";
return os;
}
I get a linker error saying that the right symbol is undefined.
I understand that this is because this templated function is not explicitly instantiated when the class is. Is there a way to get around this other than to include the .t.hpp
file any time I want to use operator<<
on the class, or to move the templated function code into the .hpp
file? Can I explicitly instantiate the function code?