C/C++ Arena

Step 1 of 8

Function templates

Suppose you want a biggest(a, b) function for ints, for doubles and for strings. Without templates you'd write three nearly identical functions. A template lets you write it once, with a placeholder for the type. The compiler then generates a real function for each type you actually use.

#include <iostream>
#include <string>

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

template <typename T>
void show_twice(const T& x) {
    std::cout << x << " " << x << "\n";
}

int main() {
    std::cout << biggest(3, 9) << "\n";                    // T = int
    std::cout << biggest(2.5, 1.0) << "\n";                // T = double
    std::cout << biggest<std::string>("pear", "apple") << "\n";
    show_twice('z');
    show_twice(std::string("hey"));
}
9
2.5
pear
z z
hey hey

How it works

Common mistakes

Your turn: make clamp_value a template.

Next: Templates over containers