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.

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


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS