Hello, I’m Liang Tang.

This is part 39 of the EasyC++ series on function templates.

For those who want a better reading experience, visit github repository: EasyLeetCode.

A function template

A function template is essentially a function defined using generics.

When we use vectors, we can define vectors of various types, we can define vectors that store ints, we can define vectors that store floats, we can define other types. We pass the stored type as an argument to the template when we declare it.

A generic type can be replaced with a specific type, such as (int or double). By passing the type as an argument to the template, the compiler generates functions of that type based on the argument type passed. This approach is also known as general programming or parameterized typing.

To take a very simple example, let’s say we want to implement a function that swaps the values of two variables. We’ll do it again for ints, we’ll do it again for doubles, and if we need other types, we’ll do a lot more of the same logic. Of course you could copy the code, but obviously that would be a waste of time and would make the code bloated.

Function templates allow you to define functions of any type, so we can do this automatically:

template <typename T>
void swap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}
Copy the code

When we create a template, we first declare the template’s type, which is what the template statement does. The keyword typename is also required, and class can be used instead. The typename keyword was added to the C++98 standard, so earlier versions tend to use class. In this scenario, the two approaches are equivalent. Typename is preferred to class in C++ Primer.

The typename is followed by the name of the type. We can use any name we like, but the letter T is customary. We’re using it just like a normal function, just like a normal function.

template <typename T>
void swap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}

int i = 10, j = 20;
swap(i, j);
double a = 3.0, b = 4.0;
swap(a, b);
Copy the code

Although we only implemented the function once, at compile time, the compiler generated multiple versions of the function depending on how we used it. For example, in the above code, we use both int and double functions. The compiler will generate two copies of the code for us, which means that the final code will be the same as if we had manually implemented the function overloading, which can be understood as a convenient feature for us to write programs.