Compilation and Template Instantiation
Unlike regular functions and classes, templates are not compiled until they are instantiated with a specific type. This means that the compiler needs to see the entire template definition whenever it encounters a usage of that template.
// header file: mytemplate.h
template <typename T>
T add(T a, T b) {
return a + b;
}
// source file: main.cpp
#include "mytemplate.h"
int main() {
int result = add(5, 10);
return 0;
}
When the main.cpp file is compiled, the compiler needs to know the entire implementation of the add function template to generate the appropriate code for the add(5, 10) call. If the implementation of the template is not visible, the compiler won’t be able to generate the necessary code.
Why can templates only be implemented in the header file?
Templates are a powerful feature in C++ that allows for the creation of generic functions and classes. They provide a way to write code that works with different data types without sacrificing type safety. However, one notable restriction when working with templates is that their implementation is often required to be in the header file. This limitation arises due to the way C++ templates are compiled and instantiated.