Home >Backend Development >C++ >Why Must Template Class Implementations and Declarations Reside in the Same Header File?
Problem:
Why is it essential to have both the implementation and declaration of a template class in the same header file?
Answer:
To understand the significance of housing the implementation and declaration of a template class in the same header file, consider the process of template instantiation.
The compiler requires access to the complete template definition, not just the signature, to generate code for each template instantiation. This means that the definitions of the template functions must be included in the header file.
Example:
// header.h template <typename T> class MyTemplate { public: MyTemplate(T n) { value = n; } void setValue(T n) { value = n; } T getValue() { return value; } private: T value; }; // source.cpp #include "header.h" // includes implementation // code that uses the template int main() { MyTemplate<int> obj(10); obj.setValue(5); cout << obj.getValue(); // outputs 5 }
In this example, the implementation of the MyTemplate functions is included in the header. When the template is instantiated (e.g., MyTemplate
By placing both the implementation and declaration in the same header, you ensure that the compiler has all necessary information at compile-time to correctly instantiate the template for each specific type.
The above is the detailed content of Why Must Template Class Implementations and Declarations Reside in the Same Header File?. For more information, please follow other related articles on the PHP Chinese website!