Template Specialization

Template Specialization

Templates are generic due to their type unawareness. However, there are cases where you need a special behavior for a specific type. C++ supports these cases by means of template specialization. A specialized template is defined explicitly for handling a certain type. This feature is useful when you want to optimize your template by overriding the general template definition, or when the general behavior is inadequate for a specific type. For example, the following template returns the lower of its two arguments:

 template < class T > T min(T f, T s){	return f < s? f: s; }

Although this algorithm is efficient, it does not work appropriately on c-strings. Instead of returning the lower string according to a lexical comparison, it merely returns the lower memory address. In order to avert this problem, a specialized version of the template is defined. Whenever the compiler has to instantiate the min template, it will use the following specialized version for arguments of type const char * and the general version for all other types:

 template <> //the empty angular brackets signal a specialized version of an existing template  const char * min(const char * f,  const char * s) {	int n = strcmp(f, s); //lexical comparison	return n > 0? s : f; //return the lower value string rather than the lower address}

The min template can be used like this:

 int n = 1, m=5;const char *f = "first"; const char *l = "last";int lowerint = min(n,m); //non-specialized version of min called; lower = 1const char *lowerchar = min(f, l); //specialized version called, lowerchar = "first"

Notes about template specializations:
1. The types must match exactly, for example, char *, unsigned const char * or const char [8] types are all different from const char * and hence, the compiler will not call the above specialized version for any of these.
2. Any number of specializations is allowed. In our case, we could have defined a special version for wchar_t strings or string objects as well.
3. All specializations have to appear in the source file after the general version.

See also  How College Students Can Shape the Future of Tech Responsibility

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