Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.
What if we want a different code for a particular data type? Consider a big project that needs a function sort() for arrays of many different data types. Let Quick Sort be used for all datatypes except char. In case of char, total possible values are 256 and counting sort may be a better option. Is it possible to use different code only when sort() is called for char data type?
It is possible in C++ to get a special behavior for a particular data type. This is called template specialization.
Another example could be a class Set that represents a set of elements and supports operations like union, intersection, etc. When the type of elements is char, we may want to use a simple boolean array of size 256 to make a set. For other data types, we have to use some other complex technique.
An Example Program for function template specialization
For example, consider the following simple code where we have general template fun() for all data types except int. For int, there is a specialized version of fun().
The main template fun(): a Specialized Template for int type: 10 The main template fun(): 10.14
An Example Program for class template specialization
In the following program, a specialized version of class Test is written for int data type.
Specialized template object General template object General template object
How does template specialization work?
When we write any template based function or class, compiler creates a copy of that function/class whenever compiler sees that being used for a new data type or new set of data types(in case of multiple template arguments).
If a specialized version is present, compiler first checks with the specialized version and then the main template. Compiler first checks with the most specialized version by matching the passed parameter with the data type(s) specified in a specialized version.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- is_pointer Template in C++
- is_void template in C++
- is_volatile template in C++
- is_fundamental Template in C++
- is_unsigned template in C++
- is_signed template in C++
- is_final template in C++14
- is_const Template in C++
- is_arithmetic Template in C++
- is_reference Template in C++
- is_lvalue_reference Template in C++
- std is_object Template in C++
- std is_union() template in C++
- is_scalar template in C++
- std::is_compound Template in C++