The definition of a class template and the implementation of its member functions has to be visible to every place that instantiates it with a distinct type. i.e. in order to instantiate myTemplate
you need to see the full definition and implementation of myTemplate
.
The easiest way to do this is to put the definition of the template and its member functions in the same header, but there are other ways. For example, you could put the member function implementations in a separate file that was included separately. You could then include it from the first header, or only include the implementation file where you needed it.
For example, one practise is to explicitly instantiate a template for distinct set of parameters in one .cpp file and declare those instantiations extern
in the header. This way, those instantiations can be used in other source files without requiring the implementation of the template member functions to be visible. However, unless you include the implementation file you won't be able to use other sets of template parameters.
i.e. if you have myTemplate
and myTemplate
defined as extern
then you can use them fine, but if myTemplate
is not defined extern
then you cannot use that without the implementation.