Templates allow us to write generic classes (called template classes) and generic functions(called template functions) that can work with generic data-types.
It is the responsibility of the compiler to create their specialized forms during the compilation step. Keywords template, typename and class are used to create templates in C++;
A template class deals with template parameters whereas a template function deals with both template parameters and function parameters.
In case of a template function with parameters, compiler can deduce the data-types based on the arguments passed to this function. But in case of a template function with no parameters as well as a template class, the data-types must be explicitly specified during function invocation and during the creation of the class instance respectively.
It is possible to pass type arguments (int,string etc) as well as non-type arguments (3,”hello” etc) as template parameters. Non-type arguments are usually passed in order to maintain state information. Non-type arguments must not be variables but constants as they need to be known at compile time.
Say we need to write a sort method that works with integer type, float type, char type, string type etc. We can write a separate sort() method for each of these types. But that is cumbersome and creates a lot of redundant code. It is in such scenarios that template functions come to our rescue. We can write a single sort() method that accepts a generic type as its argument. Now, its up to the compiler to create the specialized forms of this generic function if needed in the program.
1 3 4 6 b p r w are hello how you
It is also possible to create our own specializations of a given template function. For example, consider the previous example. But there is a new requirement that if the input type is a string, sort() should perform sort in descending order. The rest of the requirement remain the same.
1 3 4 6 b p r w you how hello are
In the example below, the first template parameter is a non-type parameter whereas the second template parameter is a type parameter. As you can see, it is also possible to provide default values to the template parameters.
3 20 4.8
While creating a template class, we can either put the class definition and the implementation in a single header file(.h) or we can keep the class definition in a header file(.h) and the implementation in a separate .cpp file. But in the latter case, the .cpp file should also contain the following piece of code for each type that might be used with the template class.
C++14 has introduced a new type of templates called as variable templates. Please go through this article to learn more about them.