After this lesson, you will be able to: Write function and class templates, use template specialization, and apply C++20 concepts.
Templates are how C++ does generics. They generate per-type optimal code at compile time, zero overhead, ugly errors, immense power.
Same function, multiple types, compiler stamps out a version per type used.
// Generic max functiontemplate <typename T>T max_of(T a, T b) {return (a > b) ? a : b;}max_of(3, 7); // T deduced as intmax_of(3.14, 2.71); // T deduced as doublemax_of(std::string("a"), std::string("b")); // T deduced as string// Explicit type parameter (if you can't deduce)int x = max_of<int>(3, 7);// auto return type (C++14+)template <typename T, typename U>auto add(T a, U b) {return a + b; // return type deduced from a + b}
Build your own generic container.
// Generic stacktemplate <typename T>class Stack {std::vector<T> data_;public:void push(const T& v) { data_.push_back(v); }void pop() { data_.pop_back(); }T& top() { return data_.back(); }bool empty() const { return data_.empty(); }};Stack<int> intStack;Stack<std::string> strStack;// Template specialization: provide a different impl for one typetemplate <>class Stack<bool> {// Pack bools as bits for memory efficiency// ... custom impl};
Before concepts, template errors were impossible to read. Concepts fix that.
#include <concepts>// Old (C++17): SFINAE, ugly errors// New (C++20): concepts, clear errorstemplate <typename T>requires std::integral<T>T square(T x) { return x * x; }square(5); // OK, int is integral// square(3.14); // ERROR, clear: '3.14 is not integral'// Shorthand: requires-clause via autoauto square2(std::integral auto x) { return x * x; }// Define your own concepttemplate <typename T>concept Numeric = std::integral<T> || std::floating_point<T>;template <Numeric T>T scale(T x, T factor) { return x * factor; }
Pick the cleanest answer.
Putting template definitions in .cpp files (must be in headers, the compiler needs the full definition to instantiate). Over-templatizing (every fn template = slower builds). Not using concepts in C++20+ code. Excessive SFINAE in C++17 code when a simple overload would do.
Sign in and purchase access to unlock this lesson.