4. Templates #
Created Wednesday 22 January 2020
- These are used to help us when data types are the only thing that change in a class’s private members or function’s parameters.
- typename just replaces T everywhere, nothing more nothing less.
syntax:
- For template definition:
template <typename typevariable1, _typename type_variable2> function or class.
- For declaring templated class object:
_classname _<data_type1, data_type2…> objectname; For using objects, no further template spec is required.
- For using template functions:
function_name <data_type1, data_type2> (arg1, arg2);
The following things are allowed:
- The param variable’s data type may be anything - user defined classes too.
- Using default values for the type_variable, i.e just write typename = data_type.
- All rules of default functions hold. Except that default type_variables on the left can be used to initialize the the typevariables on the left. This is allowed as we are not dealing with values, but only data types.
- We can omit the places where the default type has been given. for single typename, omit any mention of <>if you don’t have to.
- In declaration of objects, cascading is allowed to any level we wish.
e.g Pair <Pair<int, int>, char> Note that
-
Pair<int, int> is a valid data type.
-
We have to call functions in a cascading fashion too, to get the innermost levels.
-
This is used if Pair was given and we wanted a triplet.
-
We can write return types also using the<> notation.
-
About templates, when we write an object inside a templated class, it is automatically assume to be of type T, unless stated otherwise.
First one is implicit, while the second one is explicit.
Note:
- We need to write the template declaration over every class and function.