Template (C++)

A template lets you write a function or class that works with any type, with the actual type filled in when you use it. This is how C++ supports generic, reusable code.

C++

Instead of writing a separate max function for ints, doubles, and strings, you write one template and the compiler generates the specific versions you need. The type placeholder is usually named T.

Templates power the whole Standard Template Library: std::vector<int> and std::vector<std::string> come from the same vector template.

Syntax

template <typename T> T name(T a, T b) { ... }

Examples

C++

#include <iostream>

template <typename T>
T maxOf(T a, T b) {
    return a > b ? a : b;
}

int main() {
    std::cout << maxOf(3, 7) << std::endl;
    std::cout << maxOf(2.5, 1.5) << std::endl;
    return 0;
}

Output:

7
2.5

Learn it in a lesson

See also

Back to the Dictionary