Template In C++
Templates is a concept which enable us to define generic classes and functions and thus provides support for generic programming. Generic programming is an approach where generic types are used as parameters in algorithm so that they work for variety of suitable data types and data structures.
A template can be considered as a kind of macro. When an object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the template are sometimes called parameterized classes or functions.
Consider the example of the maximum() function, which returns the maximum of two arguments. All of the following variations make sense:
This approach works. C++ selects the best match, maximum(int, int), for a reference such as maximum(1, 2). However, creating the same function for each type of variable is a sheer waste of time. The source code for all the maximum(T, T) functions follows the same pattern, where T is one of the numeric types. It would be so convenient if you could write the function once and let C++ supply the type T as needed when the function is used. In fact, C++ lets you do this. These are called template definitions.
A template function enables you to write something that looks like a function but uses one or more type holders that C++ converts into a true type at compile time.
The following MaxTemplate program defines a template for a generic maximum() function:
The keyword template is followed by angle brackets containing one or more type holders known as template parameters, each preceded by the keyword class, a constant, or both. In this case, the definition of maximum<T>(T, T) will call the "unknown type" T. Following the angle brackets is what looks like a normal function definition. In this case, the template function T maximum<T>(T t1, T t2) returns the larger of two objects t1 and t2, each of which is of type T, where T is a class to be defined later.
A template function is useless until it is converted into a real function. C++ replaces T with an actual type known as a template argument. The main() function first invokes the template definition, passing two arguments of type int. In this case, C++ can instantiate the template providing int as the definition for T.
Creating a function from a template is called instantiating the template.
The second call is a problem—no single type can be provided for T in the template definition that matches both the int first argument and double second argument. Here the explicit reference instantiates the function maximum(double, double). C++ promotes the int argument 1 to the double 1.0 before making the call.
The output from this program appears as follows:
The maximum of -1 and 2 is 2
The maximum of 1 and 2.5 is 2.5
Press any key to continue
C++ also allows the programmer to define template classes. A template class follows the same principle of using a conventional class definition with a placeholder for some unknown support classes. For example, the following TemplateVector program creates a vector for any class that the user provides. (A vector is a type of container in which the objects are stored in a row; an array is the classic vector example.)
The intFn() function creates a vector of integers with room for 10 with the declaration:
The program reads integer values from the keyboard, saves them off, and then spits the values back out using the functions provided by TemplateVector.
The second function, nameFn(), creates a vector of Name objects. Again, the function reads in names and then displays them back to the user.
The TemplateVector handles both int values and Name objects with equal ease.
A sample output appears as follows (I've bolded input from the keyboard):
Enter integer values to add to a vector
(Enter a negative number to terminate):
Here are the numbers you entered:
Enter names to add to a second vector
(Enter an 'x'
Here are the names you entered
Press any key to continue . . .
The output of the program will be:-
1.23 and 123
100 and W
A template function may be overloaded either by template functions or ordinary fucntions of its name. In such cases, the overloading resolution is accomplished as follows:-
An error is generated if no match is found.Note that automatic conversions are applied to arguments on the template functions.
We have seen that a template can have multiple arguments. It is also possible to use non-type argument. That is, in addition to the type argument T, can also use other arguments such as strings, functions names, constant expressions and built-in types. Consider the following examples:-
array<int,10> a1; Array of 10 integers
array<float,5> a2; Array of 5 floats
array<char,20> a3; //String of size 20
You should remember a few things when using templates. First, no code is generated for a template. (Code is generated after the template is converted into a concrete class or function.) This implies that a .cpp source file is almost never associated with a template class. The entire template class definition, including all the member functions, is contained in the include file so that it can be available for the compiler to expand.
Second, a template class does not consume memory. Therefore, there is no penalty for creating template classes if they are never instanced. On the other hand, a template class uses memory every time it is instanced. Thus, the code for Array<student> consumes memory even if Array<int> already exists.
Finally, a template class cannot be compiled and checked for errors until it is converted into a real class. Thus, a program that references the template class Array<T> might compile even though Array<T> contains obvious syntax errors. The errors won't appear until a class such as Array<int> or Array<Student> is created.
Re: Template In C++
is this any similarity between generic pointers and templates,
what are the most significant use of templates and generic pointers.
please describe both terms.
Re: Template In C++
If you liked this article do nominate this article for Article of the month - May 2010
|All times are GMT +5.5. The time now is 07:21.|