Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Non-type template parameter

A non-type template parameter (NTTP) represents a value rather than a type. It lets you establish properties such as a buffer's size at compile time instead of passing them as function arguments.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

template<int N> struct Buffer;
template<auto V> struct Value;

In template<int N>, the identifier N is a non-type template parameter. Unlike typename T, it represents a value, not a type. The spelling Buffer<3> supplies a template argument; it is not a function call with a runtime argument.

In C++23, an argument for an int template parameter must be a converted constant expression of type int if it is not a braced-init-list. You can use 3 or a suitable constexpr constant, but not a value known only at runtime. A braced-init-list can also be used: Buffer<{3}> is valid under the constant-initialization rules. In template<auto V>, the parameter's type is deduced from the argument; auto does not remove template-argument restrictions.

Permitted types include scalar types, lvalue references, and certain structural class types. Not every class qualifies. The current standard draft uses the name constant template parameter; this entry describes the mechanism available in C++23.

In the example, N determines the array bound, and static_assert rejects nonpositive sizes. The elements of data remain mutable at runtime: a constant template argument does not make the entire object immutable.

Examples

#include <iostream>

template<int N>
struct Buffer {
    static_assert(N > 0);
    int data[N]{};

    constexpr int size() const { return N; }
};

int main() {
    Buffer<3> buffer;
    static_assert(buffer.size() == 3);
    buffer.data[1] = 7;
    std::cout << buffer.size() << ' ' << buffer.data[1] << '\n';
}

Result

3 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources