- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why can C++ templates only be implemented in the header file?
When you instantiate a template in C++, the compiler creates a new class. This class has all the places where you placed the template arguments replaced with the actual argument you pass to it when using it. For example −
template<typename T> class MyClass { T foo; T myMethod(T arg1, T arg2) { // Impl } };
And somewhere in your program use this class,
MyClass<int> x;
The compiler creates a new class upon encountering this for every type argument you pass it. For example, if you created 3 objects with different template arguments you'll get 3 classes, which would be equivalent to −
class MyClassInt { int foo; int myMethod(int arg1, int arg2) { // Impl } };
In order to do so, the compiler needs to have access to the implementation of the class and the methods before it encounters such statements, to instantiate them with the template argument (in this case int). If these template class implementations were not in the header, they wouldn't be accessible and hence won't compile.