C/C++ Arena

Step 6 of 8

Values as template parameters

Template parameters don't have to be types. A non-type template parameter is a compile-time value, usually a size:

template <typename T, std::size_t N>
class Ring { T items_[N]; /* ... */ };

Ring<int, 8> r;    // N is 8, baked in at compile time

That's exactly how std::array<int, 5> works. The size lives in the type, so there's no heap allocation, and Ring<int, 8> and Ring<int, 16> are different types.

Your turn: write template <typename T, std::size_t N> class FixedStack backed by a plain array T items_[N]:

Previous: if constexpr Next: Template specialization