Why should the implementation and the declaration of a template class be in the same header file? Could any of you explain it by example?
To have all the information available, current compilers tend to require that a template must be fully defined whenever it is used. That includes all of its member functions and all template functions called from those. Consequently, template writers tend to place template definition in header files.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates.
Even in plain C, it is possible to put code in a header file. If you do it, you usually need to declare it static or else multiple . c files including the same header will cause a "multiply defined function" error.
Definition. As per the standard definition, a template class in C++ is a class that allows the programmer to operate with generic data types. This allows the class to be used on many different data types as per the requirements without the need of being re-written for each type.
The compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template, so you need to move the definitions of the functions to your header.
For more details read about The Inclusion Model.
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<int>
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<int>
and myTemplate<std::string>
defined as extern
then you can use them fine, but if myTemplate<double>
is not defined extern
then you cannot use that without the implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With