C++C++
AdvancedLesson 14 of 18

Templates and Generic Programming – C++

Function and class templates, variadic templates and fold expressions.

Templates generate code for arbitrary types at compile time – with no runtime cost. This is the foundation of the entire STL (std::vector<T>, std::sort ...).

#include <iostream>
#include <string>

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

int main() {
    std::cout << maximum(3, 7) << '\n';                                // 7 (T = int)
    std::cout << maximum(2.5, 1.5) << '\n';                            // 2.5 (T = double)
    std::cout << maximum(std::string("Ada"), std::string("Bob")) << '\n';   // Bob
    std::cout << maximum<double>(1, 2.5) << '\n';                      // 2.5 (explicit)
}

Classes can be templates too. The compiler generates a separate class for every type combination used (instantiation).

#include <iostream>
#include <utility>
#include <vector>

template <typename T>
class Stapel {
public:
    void push(T wert) { daten_.push_back(std::move(wert)); }
    T pop() {
        T w = std::move(daten_.back());
        daten_.pop_back();
        return w;
    }
    bool leer() const { return daten_.empty(); }
    std::size_t groesse() const { return daten_.size(); }
private:
    std::vector<T> daten_;
};

int main() {
    Stapel<int> s;
    s.push(1);
    s.push(2);
    int oben = s.pop();
    std::cout << oben << ' ' << s.groesse() << '\n';   // 2 1
}

Variadic templates accept any number of arguments, and fold expressions (C++17) combine them with an operator. if constexpr branches at compile time depending on the type:

#include <iostream>
#include <string>
#include <type_traits>

template <typename... Args>
auto summe(Args... args) { return (args + ...); }

template <typename T>
std::string beschreibe(const T& x) {
    if constexpr (std::is_integral_v<T>) return "integer " + std::to_string(x);
    else                                 return "something else";
}

int main() {
    std::cout << summe(1, 2, 3, 4) << ' ' << summe(1.5, 2) << '\n';   // 10 3.5
    std::cout << beschreibe(42) << ", " << beschreibe(2.5) << '\n';
}
TipThanks to CTAD (Class Template Argument Deduction, C++17), you write std::pair p{1, 2.5}; or std::vector v{1, 2, 3}; without specifying types.
WarningTemplates belong entirely in the header (the compiler needs the definition when instantiating). Error messages for template errors are long and cryptic – concepts (see below) make them much more readable. maximum(1, 2.5) fails because T is deduced contradictorily.