C++ · Module 12 · Lesson 11 min read

Function Templates

The problem

c
int max_int(int a, int b);
double max_double(double a, double b);
std::string max_string(...);   // same logic, repeated 😩

A function template

scss
template <typename T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}
maximum(3, 7);            // T = int
maximum(2.5, 1.5);        // T = double
maximum<std::string>("apple", "banana");   // T given explicitly

typename and class mean the same thing here.

How it works: instantiation

The template is a recipe. When you call it with a type, the compiler generates (instantiates) a real function for that type at compile time. No runtime cost.

Template argument deduction

The compiler deduces T from the arguments. If they conflict, it fails:

scss
maximum(3, 2.5);          // ❌ T = int or double?
maximum<double>(3, 2.5);  // ✅ explicit

Multiple template parameters

arduino
template <typename T, typename U>
auto add(T a, U b) { return a + b; }   // return type deduced

Non-type template parameters

arduino
template <int N>
int multiply(int x) { return x * N; }
multiply<3>(10);   // 30

Abbreviated templates (C++20)

scss
auto twice(auto x) { return x + x; }   // shorthand for a template

Requirements on T

The template only works if T supports the operations used (> in maximum). Errors appear when instantiated — often long messages. Concepts (lesson 12.5) make requirements explicit.

Templates live in headers

The compiler needs the full definition to instantiate → put templates in .h files.

Example

C++
#include <iostream>
#include <string>
#include <vector>

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

template <typename T>
T sum(const std::vector<T>& values) {
    T total{};                          // zero for numbers, "" for strings
    for (const T& v : values) total += v;
    return total;
}

template <typename T, typename U>
auto multiply(T a, U b) { return a * b; }   // return type deduced

template <int Percent>
double apply_tax(double amount) { return amount * (100 + Percent) / 100.0; }

auto twice(auto x) { return x + x; }        // C++20 abbreviated template

template <typename T>
void print_all(const std::vector<T>& v) {
    for (const auto& x : v) std::cout << x << ' ';
    std::cout << '\n';
}

int main() {
    std::cout << "maximum(3, 7) = " << maximum(3, 7) << '\n';
    std::cout << "maximum(2.5, 1.5) = " << maximum(2.5, 1.5) << '\n';
    std::cout << "maximum<std::string>(\"apple\", \"banana\") = " << maximum<std::string>("apple", "banana") << '\n';
    std::cout << "maximum<double>(3, 2.5) = " << maximum<double>(3, 2.5) << '\n';
    // maximum(3, 2.5);                     // error: T deduced as both int and double

    std::cout << "sum of ints: " << sum(std::vector<int>{ 1, 2, 3, 4 }) << '\n';
    std::cout << "sum of doubles: " << sum(std::vector<double>{ 0.5, 1.25 }) << '\n';
    std::cout << "sum of strings: " << sum(std::vector<std::string>{ "Budget", "Buddy" }) << '\n';

    std::cout << "multiply(4, 2.5) = " << multiply(4, 2.5) << '\n';
    std::cout << "apply_tax<13>(1000) = " << apply_tax<13>(1000) << ", apply_tax<5>(1000) = " << apply_tax<5>(1000) << '\n';
    std::cout << "twice(21) = " << twice(21) << ", twice(std::string(\"ha\")) = " << twice(std::string("ha")) << '\n';
    print_all(std::vector<char>{ 'C', '+', '+' });
    return 0;
}

/* Output:
maximum(3, 7) = 7
maximum(2.5, 1.5) = 2.5
maximum<std::string>("apple", "banana") = banana
maximum<double>(3, 2.5) = 3
sum of ints: 10
sum of doubles: 1.75
sum of strings: BudgetBuddy
multiply(4, 2.5) = 10
apply_tax<13>(1000) = 1130, apply_tax<5>(1000) = 1050
twice(21) = 42, twice(std::string("ha")) = haha
C + +
*/