Where Should Template Definitions Appear?

Where Should Template Definitions Appear?

Normally, you declare functions and classes in a .h file and place their definition in a separate .cpp file. With templates, this practice isn’t really useful because the compiler must see the actual definition of a template, not just the declaration, when it encounters a template instantiation. Therefore, it’s best to place both the template’s declaration and definition inside the same .h file. For this reason, all STL header files contain template definitions rather than mere declarations.

In the future, when compilers supporting the “export” keyword become available, it will be possible to use only the template’s declaration and leave the definition in a separate source file.


Share the Post: