Why can C++ templates only be implemented in the header file?

C++Server Side ProgrammingProgramming

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.

Updated on 11-Feb-2020 10:14:53