Exported Templates Can Reduce Compilation Time

Exported Templates Can Reduce Compilation Time

A template definition can be #included in several translation units (source files). However, each time it is #included the definition is recompiled. Using large template definitions can increase compilation time significantly.

A better solution is to compile the template definition only once, and use just the template’s declaration in each translation unit. This is very similar to how a global function is treated: its definition is compiled only once and thereafter, only its prototype is required.

In order to avoid repeated compilations of a template, you should precede its definition with the keyword export:

 	//file min.cppexport template < class T > T min (const T& a, const T& b) { return a > b ? b : a;}

A separate header file should contain the declaration of the template:

 	//file min.h	template < class T > T min (const T & a, const T & b); //declaration only

In all other translation units, only the declaration is now required:

 	#include "min.h"	void main() {	int smaller = min(10, 5);}

Please note that exported templates are relatively new in C++; therefore, not all compilers support this feature yet.


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