Templates in C++

C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code that behaves the same for data of any type. 

Suppose you write a function printData:

void printData(int value)
{
        std::cout<<"The value is "<<value<<std::endl;
}

If you later decide you also want to print double values, or std::string values, then you have to overload the function:

void printData(double value)
{
        std::cout<<"The value is "<<value<<std::endl;
}
void printData(std::string value)
{
        std::cout<<"The value is "<<value<<std::endl;
}

The actual code written for the function is identical in each case; it is just the type of the variable value that changes, yet we have to duplicate the function for each distinct type. This is where templates come in - they enable the user to write the function once for any type of the variable value.

template<typename T>
void printData(T value)
{
        std::cout<<"The value is "<<value<<std::endl;
}


Templates are of two types:
  • Function Templates
  • Class Templates

Function Templates:

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

Class Templates:

We also have the possibility to write class templates, so that a class can have members that use template parameters as types.

No comments:

Post a Comment