Non-Type Template Parameters in C++
Templates accept values as well as types: template <typename T, std::size_t N> class Array bakes the constant N into the type, which is exactly how std::array<int, 5> differs from std::array<int, 6>. Values must be compile-time constants — literals, constexpr variables, enumerators — never run-time input.
This lifts sizes, capacities, and policy integers into the type system, enabling bounds the compiler checks and loops it can unroll. C++20 extends non-type parameters to floating-point, class-type (structural), and more — constants as first-class template citizens.
Values in angle brackets
Buffer<int, 1024> fixes capacity 1024 at compile time — part of the type, distinct from Buffer<int, 512>.
Constants only
Arguments must be compile-time-known (constexpr, literals) — a run-time int variable is rejected, since types can't depend on run time.
Sizes become checkable
Fixed extents enable static_assert capacity checks and bound-safe access patterns the compiler verifies.
C++20 widens the set
Structural class types and floating-point values joined the allowed list — string-literal parameters and fixed-point constants included.
#include <iostream>#include <cstddef> template <typename T, std::size_t N>class Fixed { T data[N];public: constexpr std::size_t size() const { return N; }}; int main() { Fixed<int, 4> f; std::cout << f.size() << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.