If you are using .h/.cpp file pairs to organize your code, there are some special restrictions about where you place your templated code. (If you are using modules, there is nothing new to consider.) When you are using header/cpp file pairs to organize your code, all of your templated code including function definitions should be placed directly into header files.
This is different than for non-templated code. A regular function will be declared in the .h file and defined in the .cpp file. The definition will be compiled as soon as the compiler sees it, and we want to make sure that only one instance of the function is created.
However, templated code is not compiled directly. It instead provides a blueprint for generating code. If you try to put the templated code in a separate file (call it library.cpp), the compiler will do the following:
Compile library.cpp and see something like template<typename T> myMax(T a, T b)... but it wonβt know what types to build versions of that function for.
Compile main.cpp and try to use myMax with a specific type like int. But since the definition is not available, it wonβt be able to generate the code.
In the place the template definition is available, the compiler does not know what to build, and in the place where it knows what to build, the definition is not available!
To resolve this, we need to include the full definition of the templated function or class in the header file. That way, in whatever file we try to use the templated code, the compiler will have access to the full definition and can generate the appropriate code. To indicate that this header file contains templated code, some developers will name this file with a different extension, like .hpp.
Figure23.5.2.Placing all the templated code in the header means the compiler has the needed template blueprint when it discovers a use of the template.
This means that if you have a library of templated code, you will likely not even need a separate .cpp file for implementations as they all should be in the header. Instead of myTemplatedLibrary.h and myTemplatedLibrary.cpp you would likely just have myTemplatedLibrary.h.
#ifndef MYTEMPLATEDLIBRARY_H
#define MYTEMPLATEDLIBRARY_H
// The full definition of the templated function must be in the header file
template <typename T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
#endif
Warning23.5.1.
If you are using header/cpp file pairs to organize your code, all of your templated code including function definitions should be placed directly into header files.