`template` — C++ Keyword
`template` — C++ Keyword
The template keyword in C++: defines generic functions, classes, variables, and alias templates.
`template` — C++ Keyword
The template keyword in C++: defines generic functions, classes, variables, and alias templates.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
templateIntroduces a template, enabling generic programming. Templates are instantiated by the compiler for each unique set of template arguments.
template <parameter-list> declaration
// Explicit instantiation
template class Name<Args>;
// Explicit specialization
template <> class Name<SpecificType> { ... };
#include <print>
// Function template
template <typename T>
T max_of(T a, T b) {
return a > b ? a : b;
}
// Class template
template <typename T, int N>
class FixedArray {
T data_[N]{};
public:
T& operator[](int i) { return data_[i]; }
int size() const { return N; }
};
// Variable template (C++14)
template <typename T>
constexpr T pi = T(3.14159265358979);
int main() {
std::println("{}", max_of(3, 7)); // 7
std::println("{:.2f}", max_of(1.5, 2.8)); // 2.80
FixedArray<int, 4> arr;
arr[0] = 42;
std::println("{}", arr[0]); // 42
std::println("{:.6f}", pi<double>); // 3.141593
}
if constexpr inside templates avoids instantiating branches that would otherwise be ill-formed.templateint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}