C++ Templates
C++ templates let you write code once and use it with many types. The compiler generates a specific version for each type you use, so templates are both flexible and fast. The entire Standard Library is built on them.
Function Templates
#include <iostream>
#include <string>
template <typename T>
T biggest(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << biggest(3, 9) << '\n';
std::cout << biggest(2.5, 1.5) << '\n';
std::cout << biggest<std::string>("apple", "pear") << '\n';
}9 2.5 pear
Class Templates
#include <iostream>
#include <string>
template <typename T>
class Box {
T value;
public:
explicit Box(T v) : value(v) {}
T get() const { return value; }
};
int main() {
Box<int> a(42);
Box b(std::string("hello")); // type deduced (C++17)
std::cout << a.get() << ' ' << b.get() << '\n';
}42 hello
Constraining Templates with C++20 Concepts
Concepts state what a type must support. Errors become short and readable, and you can overload on concepts.
#include <concepts>
#include <iostream>
template <std::integral T>
bool isEven(T n) { return n % 2 == 0; }
auto half(std::floating_point auto x) { return x / 2; }
int main() {
std::cout << std::boolalpha << isEven(10) << '\n';
std::cout << half(5.0) << '\n';
// isEven(2.5); // error: double does not satisfy std::integral
}true 2.5
Template Tips
- Templates are usually defined entirely in header files.
- Use concepts to document and enforce requirements.
- Let the compiler deduce types when possible.
- Use templates for genuinely generic code, not for everything.
Frequently asked questions
What are templates used for in C++?
Templates create generic functions and classes that work with any suitable type, like std::vector<T> or std::max. They avoid duplicating code for each type.
What are concepts in C++20?
Concepts are named compile-time requirements on template parameters, like std::integral. They produce clear errors and make template interfaces self-documenting.
Why must templates be in header files?
The compiler needs the full template definition to generate code for each type it is used with, so the definition must be visible wherever it is used.