Learn C++
#include "templates/nontype_params.hpp"

Non-Type Template Parameters in C++

//concept

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.

//how it works
1

Values in angle brackets

Buffer<int, 1024> fixes capacity 1024 at compile time — part of the type, distinct from Buffer<int, 512>.

2

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.

3

Sizes become checkable

Fixed extents enable static_assert capacity checks and bound-safe access patterns the compiler verifies.

4

C++20 widens the set

Structural class types and floating-point values joined the allowed list — string-literal parameters and fixed-point constants included.

//example
#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;
}
Output
4
1Fixed<int, 4> stamps a class whose storage is a genuine int[4] — N is a compile-time constant throughout.
2size() returns N as constexpr, usable in further compile-time contexts.
34 prints — the value parameter survived from angle brackets into run-time behavior.
//use cases
Fixed-capacity buffers and ring queues with zero dynamic allocation
Dimension-checked matrices where mismatched extents fail at compile time
std::array-style containers parameterized by element type and count
Bitset widths and protocol field sizes baked into types

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.