Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Advanced
Sep 17, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.cpp
export 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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date