A template is a pattern the compiler stamps out a copy of for each type it is used with. template <typename T> T max(T a, T b) is not a function - it is a recipe, and max(1, 2) causes the compiler to generate an int version. This is compile-time polymorphism: unlike a virtual call, there is no runtime dispatch, nothing to look up, and the generated code is as specific as if you had written it by hand. That is the zero-cost abstraction promise, and templates are where it is delivered.
Class templates work the same way - std::vector<T> is one. Templates also take non-type parameters: template <typename T, std::size_t N> is how std::array knows its size at compile time.
Everything a template uses must be visible when it is instantiated, which is why templates live in headers rather than being split across a .h and a .cpp. That is not a style choice; the definition genuinely has to be available at the point of use.
Variadic templates take any number of arguments of any types. template <typename... Args> declares a parameter pack, and args... expands it. Before C++17 you unpacked one with recursion and a base case. Since C++17 a fold expression - (std::cout << ... << args) - does it in one line.
Concepts, from C++20, are the fix for the one thing everybody hates about templates: the errors. Pass a type without operator< to an unconstrained max and you get pages of instantiation backtrace pointing at a line deep inside a header. A concept is a named, checkable requirement on a template argument - template <std::integral T> - and if the type does not satisfy it, the compiler says exactly that, at the call site, in one line. Concepts also serve as documentation that the compiler enforces: template <Sortable T> tells the reader what T must be, where typename T told them nothing.
#include <iostream>
#include <vector>
#include <string>
#include <concepts>
#include <type_traits>
// ---------------- A function template ----------------
template <typename T>
T largest(T a, T b)
{
return (a > b) ? a : b;
}
// The compiler generates one of these per type actually used. Nothing
// is dispatched at runtime - largest(1, 2) compiles to the comparison.
// ---------------- A class template ----------------
template <typename T, std::size_t N> // N is a NON-TYPE parameter
class FixedStack
{
public:
void push(const T& value)
{
if (count_ < N) { items_[count_++] = value; }
}
T pop()
{
return count_ > 0 ? items_[--count_] : T{};
}
std::size_t size() const { return count_; }
private:
T items_[N]{};
std::size_t count_{0};
};
// ---------------- Variadic templates ----------------
// C++17 fold expression: expands to (cout << a) << b) << c ...
template <typename... Args>
void print_all(const Args&... args)
{
(std::cout << ... << args) << '\n';
}
template <typename... Args>
auto sum_all(Args... args)
{
return (args + ... + 0); // fold with an initial value
}
// ---------------- Concepts (C++20) ----------------
// A named requirement, checked at the call site.
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template <Numeric T> // constrained: T must satisfy Numeric
T average(const std::vector<T>& values)
{
if (values.empty()) { return T{}; }
T total{};
for (const auto& v : values) { total += v; }
return total / static_cast<T>(values.size());
}
// A concept with an explicit requires-clause: this is what the
// requirement actually looks like when it is not already in <concepts>.
template <typename T>
concept Printable = requires(const T& t) {
{ std::cout << t } -> std::same_as<std::ostream&>;
};
template <Printable T>
void show(const T& t) { std::cout << t << '\n'; }
int main()
{
std::cout << largest(3, 7) << '\n'; // int version
std::cout << largest(2.5, 1.5) << '\n'; // double version
std::cout << largest<std::string>("a", "b") << '\n'; // explicit
FixedStack<int, 4> stack;
stack.push(1);
stack.push(2);
std::cout << stack.pop() << ' ' << stack.size() << '\n'; // 2 1
print_all("id=", 42, " ok=", true); // one call, four types
std::cout << sum_all(1, 2, 3, 4) << '\n'; // 10
std::cout << average(std::vector<int>{1, 2, 3, 4}) << '\n'; // 2
std::cout << average(std::vector<double>{1.0, 2.0}) << '\n'; // 1.5
// average(std::vector<std::string>{"a"});
//
// WITHOUT the concept, that would produce a wall of instantiation
// errors from inside the function body. WITH it, the compiler says:
//
// error: no matching function for call to 'average'
// note: constraints not satisfied
// note: 'std::string' does not satisfy 'Numeric'
//
// One line, at the call site, naming the actual problem. That is the
// whole argument for concepts.
show(42);
show(std::string{"printable"});
return 0;
}
Discussion
No questions on this topic yet. Sign in to ask the first one.