Why are templates usually implemented in header files rather than source files?

Last updated 21 June 2026

  • A template is a blueprint: code is generated only where it is instantiated, so the full definition must be visible in every translation unit that uses it. Otherwise you get linker errors.

  • Templates are exempt from the usual cross-TU one-definition rule, so identical header definitions are fine and the linker merges duplicate instantiations.

  • Alternatives: explicit instantiation in a .cpp (e.g. template class Foo<int>;) for a fixed set of types, or C++20 modules.

  • https://www.interviewbit.com/blog/web-stories/master-top-cpp-interview-questions/
All C++ interview questions