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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: