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.

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist