Templates - shahzade baujiti

Breaking

Wednesday, April 24, 2019

Templates

.3
Templates

Templates in C++ programming allows function or class to work on more than one data type at once without writing different codes for different data types. Templates are often used in larger programs for the purpose of code reusability and flexibility of program. The concept of templetes can be used in two different ways:
- Function Template
- Class Template

Function Template
A function templates work in similar manner as function but with one key difference. A single function template can work on different types at once but, different functions are needed to perform identical task on different data types.

The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}

Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.

Class Template
Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:

template <class type> class class-name {
.
.
.
}

Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.


No comments:

Post a Comment