Skip to content
Template Functions in C++

Template Functions in C++

Template Functions in C++ are easy to implement and powerful at the same time, also known as Generic Programming, where we don’t specify the data type and can use any type when needed. The template function follows the concept of data type as a parameter for initializing variables at compile time.

Why do we need Templates?

Consider the below example of an addition function,

int add(int a, int b)
{
    return a+b;
}

The above function adds two integers and returns the output as an integer, what if we want to pass two decimal numbers to the same function? again we need to write another function that accepts two floating-point numbers i.e decimal numbers.

float add(float a, float b)
{
    return a+b;
}

Since this was a simple and small program we don’t care much about it however, when we write complex functions re-writing all the functions for all data types will take a lot of time, space and compile-time/run-time.

Now the concept of Templates Functions can be used here where we just specify what the function needs to do and we need not worry about the data type as it will be taken care by the compiler at compile time.

Important Note

Whenever an argument of certain data types is passed to a template function the compiler generates copies of the function with the given data type, this is how template functions work.

Template Function Syntax

The template function starts with the keyword template and the <> represent the template parameters and the function declaration in the next line.

template <class T>
T functionName(T arguments)
{
   ... ... ...
//function body
}

Here T represents the data type as a parameter for the template function, and in the first line we can also use the keyword typename instead of the class keyword.

Example: Addition Function using Templates in C++

#include <iostream>
using namespace std;

template <class T>
T add(T a, T b)
{
    return a + b;
}
int main()
{
    cout << add<int>(1, 2) << endl;
    cout << add<double>(1.5, 2.5) << endl;
    return 0;
}

Output

3
3.5

Conclusion

Template functions really save a lot of time, and I’m glad we learned them today! What do you say? and by the way, this post is a part of my #30DaysChallenge to write a blog post every day on what I learn, I’ll be very happy if you can share this with a friend, Wishing you more Happiness~ Abhiram Reddy.

Tags: