Tutorials / C++: From Basics to Modern C++ / Templates: writing generic code

Templates: writing generic code

16 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

The problem templates solve

Suppose you write maxOf(int, int). Next week you need it for doubles. Then for strings. Copying the function three times is wasteful and risks the copies drifting apart. A template lets you write the logic once and let the compiler generate a version for each type you use.

Function templates

#include <iostream>
#include <string>

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

int main() {
    std::cout << maxOf(3, 9) << "\n";                       // T = int
    std::cout << maxOf(2.5, 1.5) << "\n";                   // T = double
    std::cout << maxOf(std::string{"pear"}, std::string{"apple"}) << "\n";   // T = std::string
}

The compiler works out T from the arguments. This is called template argument deduction. When you call maxOf(3, 9), it generates a real function int maxOf(int, int) for you. This generation is called instantiation, and it happens at compile time, so templates have no run-time cost compared to hand-written code.

Both arguments must deduce to the same T. The call maxOf(3, 2.5) fails, because the arguments are an int and a double. You can fix it by being explicit, maxOf<double>(3, 2.5), or by changing the design.

Templates require operations, not inheritance

The template above only needs operator< to exist for T. If you call maxOf with a type that has no <, you get a compile error, usually a long one. In older C++ the error message appeared deep inside the template body and was very hard to read. C++20 concepts, covered later, let you state the requirement up front so the error is short and clear.

Class templates

Classes can be templates too. That is exactly how std::vector<int> and std::map<K, V> work. Here is a small fixed-purpose stack.

#include <iostream>
#include <stdexcept>
#include <vector>

template <typename T>
class Stack {
public:
    void push(const T& value) { items_.push_back(value); }

    T pop() {
        if (items_.empty()) throw std::runtime_error("pop from empty stack");
        T top = std::move(items_.back());
        items_.pop_back();
        return top;
    }

    const T& peek() const {
        if (items_.empty()) throw std::runtime_error("peek at empty stack");
        return items_.back();
    }

    bool empty() const { return items_.empty(); }
    std::size_t size() const { return items_.size(); }

private:
    std::vector<T> items_;
};

int main() {
    Stack<int> numbers;
    numbers.push(10);
    numbers.push(20);
    std::cout << numbers.pop() << "\n";    // 20

    Stack<std::string> words;
    words.push("alpha");
    words.push("beta");
    std::cout << words.peek() << " " << words.size() << "\n";   // beta 2
}

Since C++17, the compiler can sometimes deduce class template arguments from constructor arguments, so std::pair p{1, 2.5}; works without writing the types. For our Stack we have to write Stack<int> because there are no constructor arguments to deduce from.

Non-type parameters and multiple parameters

A template parameter can also be a value. std::array<int, 4> is the standard example: the 4 is a template argument.

template <typename T, std::size_t N>
T sumArray(const T (&arr)[N]) {
    T total{};
    for (std::size_t i = 0; i < N; ++i) total += arr[i];
    return total;
}

int values[]{1, 2, 3, 4};
// sumArray(values) returns 10, and N is deduced as 4

Where template code lives

Here is a practical rule that catches many people out. The compiler needs to see the full body of a template when it instantiates it. So template definitions normally go in the header file, not in a .cpp. If you put a template's member function bodies in a source file, you get linker errors saying the function is undefined, even though the code looks right.

A glimpse of variadic templates

A template can accept any number of arguments using a parameter pack. You do not need this daily, but you will see it in library code.

template <typename... Args>
void printAll(const Args&... args) {
    ((std::cout << args << " "), ...);   // C++17 fold expression
    std::cout << "\n";
}

// printAll(1, "two", 3.5) prints: 1 two 3.5

Reading template errors

Template errors are famous for length. A few habits help. Read the first error only. Look for the phrase "required from here" which points at your call, not the library internals. And look for "no match for operator" or "no matching function", which usually names the missing capability. With a little practice you can usually find the line within a few seconds.

The common mistake

Writing a template that quietly assumes more than it states, for example one that needs a default constructor and copy semantics when the user passes a move-only type. Another is putting template bodies in a .cpp file. And a third, over-using templates. If a function will only ever work with int, a plain function is easier to read. Make something a template when you actually have two or more types that need it.

Try it yourself

  1. Write a template clamp3(T value, T low, T high) and test it with ints and doubles. Compare with std::clamp from <algorithm>.
  2. Extend Stack with an emplace method that takes constructor arguments and builds the item in place.
  3. Write a function template countIf that takes a vector and a predicate, and use it with a lambda.
cpp
#include <iostream>
#include <string>

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

int main() {
    std::cout << maxOf(3, 9) << "\n";                       // T = int
    std::cout << maxOf(2.5, 1.5) << "\n";                   // T = double
    std::cout << maxOf(std::string{"pear"}, std::string{"apple"}) << "\n";   // T = std::string
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account