Topic 13 of 27 · Expert
Templates & Concepts
Function/class templates, specialisation and C++20 concepts.
Concept
Templates generate type-specific code at compile time — the foundation of the STL.
Specialisation provides a custom version for a specific type. Variadic templates accept any number of arguments.
C++20 concepts constrain template parameters with readable requirements and give far clearer error messages than SFINAE.
Code (C++20)
#include <concepts>
#include <iostream>
#include <vector>
template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;
template <Number T>
T maxOf(T a, T b) { return a > b ? a : b; }
template <typename T>
class Stack {
std::vector<T> data_;
public:
void push(const T& x) { data_.push_back(x); }
T pop() { T x = data_.back(); data_.pop_back(); return x; }
bool empty() const { return data_.empty(); }
};
template <typename... Ts>
auto sum(Ts... xs) { return (xs + ...); } // fold expression
int main() {
std::cout << maxOf(3, 7) << ' ' << sum(1, 2, 3, 4) << '\n';
// maxOf("a", "b"); // error: doesn't satisfy Number
}Remember
- Templates are instantiated at compile time.
- Template definitions usually live in headers.
- Concepts > SFINAE for constraints.
Interview questions
Why are templates defined in headers?
The compiler needs the full definition to instantiate the template for each type used in every translation unit.
What are concepts?
Named compile-time predicates on template parameters (C++20) that constrain which types are accepted and improve error messages.
Lesson test
Take an 8-question test on “Templates & Concepts” — concepts, output prediction, bug spotting and interview questions.