Templates in c++
Published: 2023-08-26 16:40:50

# Templates

Templates allow you to construct both functions and classes based on types that have not yet been stated.Thus, templates are a powerful toolfor automating program code generation.

    As a programmer you will often be faced with implementing multiple versions of similar functions and classes, which are needed for various types.For example , A class used to represent an array of int values is very similar to a class representing an array of double values.
    Operations performed with elements, such as search and sort algorithms, must be defined separately for each type.

## Function and Class Templates

C++ allows you to define templates—parameterized families of related functions or classes:

> > a function template defines a group of statements for a function using a parameter instead of a concrete type

> > a class template specifies a class definition using a parameter instead of a concrete type.

### Advantages of Templates

- A template need only be coded once. Individual functions or classes are automatically generated when needed.
- A template offers a uniform solution for similar problems allowing type-independent code to be tested early in the development phase.
- Errors caused by multiple encoding are avoided.

### Templates in the Standard Library

The C++ standard library contains numerous class template definitions, such as the stream classes for input and output, string, and container classes.

The standard library also includes an algorithm library, which comprises many search and sort algorithms. The various algorithms are implemented as global function templates and can be used for any set of objects.

## DEFINING TEMPLATES

### Defining Function Templates

The definition of a template is always prefixed by

> > template\<class T>

where the parameter T is a type name used in the definition that follows. Although you must state the class keyword or 'typename', T can be any given type, such as an int or double.

```c++
template <typename T>   //template <class T>
void add(T& x, T&y){
    return x + y;
}
```

    This defines the function template add(). The parameter T represents the type of variables to add. The name T is common but not mandatory.

```c++
int main(){
    int a = 12 ,b = 23;
    cout << add(a , b) << endl;
}
```

### Defining Class Templates

Example

```c++
// stack.h : The class template Stack with
// methods push() and pop().
template <class T>
class Stack
{
private:
    T *basePtr; // Pointer to array
    int top;    // top of the stack
    int max;     // Maximum number of elements

public:
    Stack(int max){
        basePtr = new T[max];
        this->max = max;
        top = 0;
    }
    ~Stack(){
        delete[] basePtr;
    }
    bool isEmpty() { return (top == 0); }
    bool push(const T &ele);
    bool pop(T &x);
};
template <class T>
bool Stack<T>::push(const T &ele){
    if (top < max - 1){
        basePtr[top++] = ele;
        return true;
    }
    return false;
}
template <class T>
bool Stack<T>::pop(T &x){
    if (top > 0){
        x = basePtr[--top];
        return true;
    }
    return false;
}
```

### Instantiating Template Functions

A template function is instantiated when it is first called. The compiler determines the parameter type of T by the function arguments.

### Instantiation of Template Classes

The instantiation of a template class is performed implicitly when the class is used for the first time, for example, when an object of the template class is defined.

Templates will not reduce the amount of machine code required for a program. However, it does spare the programmer’s extra work required to develop multiple versions of functions and classes

Templates are double checked for errors by the compiler—once when the template definition is compiled and again during instantiation. The first check recognizes errors that are independent of the template parameters.

### Multiple Template Parameters

You can also define templates with multiple parameters

```c++
template <class T , class U>
class Stack
{

}
```

### DEFAULT ARGUMENTS OF TEMPLATES

You can define default arguments for template parameters, just as for function parameters. If an argument required to instantiate a template is missing, the default value is then used.

- if you declare a default argument for at least one parameter, you must define default values for all the remaining parameters
- if a template argument for which a default argument was declared is omitted during instantiation, all the remaining template arguments must be omitted.