C++ Function Templates

A function template is a blueprint for making functions. It lets you write one function definition that C++ can use with different data types, such as int, double, or std::string.

Templates are useful when the logic is the same but the type changes. Instead of writing separate functions like maxInt and maxDouble, you can write one template and let the compiler create the needed versions.

Basic Syntax

A function template starts with template <typename T>. The name T is a type parameter, which means it stands in for a real type when the function is used.

Inside the function, use T anywhere you would normally write a type:

template <typename T> T larger(T a, T b)

You may also see class used instead of typename in older code. For this kind of template parameter, template <class T> means the same thing as template <typename T>.

Example

This program defines a larger template for comparing two values of the same type. It also defines a showPair template with two type parameters.

#include <iostream>
#include <string>

using namespace std;

template <typename T>
T larger(T a, T b) {
    if (a > b) {
        return a;
    }
    return b;
}

template <typename First, typename Second>
void showPair(First first, Second second) {
    cout << first << " - " << second << endl;
}

int main() {
    cout << larger(4, 9) << endl;
    cout << larger(3.5, 2.1) << endl;
    cout << larger<string>("pear", "apple") << endl;

    showPair("Score", 42);
    showPair(string("Average"), 87.5);

    return 0;
}

Output:

9
3.5
pear
Score - 42
Average - 87.5

How Type Deduction Works

When you call larger(4, 9), both arguments are int, so the compiler creates and uses a version of larger where T is int. When you call larger(3.5, 2.1), it creates a version where T is double.

The call larger<string>("pear", "apple") gives the template argument explicitly. That tells C++ to treat the arguments as std::string values. The comparison uses string ordering, so pear is larger than apple.

Multiple Type Parameters

A template can have more than one type parameter. In showPair, First and Second can be different types. That is why the function can print both "Score" with an int and a std::string with a double.

When To Use Function Templates

Use a function template when one algorithm works the same way for several types. Good examples include comparing values, swapping values, printing simple pairs, or finding an item in a collection.

Do not use a template just to avoid writing clear code. A template still requires the operations inside the function to be valid for the type. For example, larger only works with types that can be compared using >.

Takeaway

Function templates let you write reusable, type-safe functions; the compiler creates the correctly typed function when you call the template.