Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Aug 20, 1998



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

How to Avoid Code Bloat When Using Templates

If you are using templates in your code, you are probably aware of their invaluable advantages. However, templates can cause a code bloat: The compiler reduplicates the template's body for each distinct type being used. In the following example, three distinct copies of the min template will be automatically generated - one for each type used:
template < class T > T min(T f, T s)
	return f < s? f: s; 
int n = 5, m= 10;
	int j = min(n,m); //min<int> instantiated
	char c = 'a', d = 'b';
	char k = min(c,d); //min<char> instantiated
	short int u = 5, v = 10;
	short int w = min(u,v);// min<short int> instantiated
Sometimes, such unnecessary instantiations can be avoided by (safely) casting the arguments into one common type:
short n = 5, m= 10;
	int j = min( static_cast<int> (n), static_cast<int> (m) ); //min<int> instantiated
	char c = 'a', d = 'b';
	char k = static_cast<char> (min( static_cast<int> (c), static_cast<int> (d) ) ); //min<int> used
This technique can also be applied to pointers: first, they have to be cast to void * and then cast back to their original type. Please note that for very small templates (like the above one), this technique is not worth the bother. Nonetheless, when templates consisting of hundreds of code lines are used (such as STL containers), you may consider its use.
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