# Non-type template parameters

> A non-type template parameter makes a compile-time value part of a type's identity. Which types may carry such values, which arguments are acceptable, and when two arguments name the same specialization all follow from one requirement, that the compiler must be able to decide template-argument equivalence.

- **Source:** C++ Atlas (https://cppatlas.com/topics/non-type-template-parameters)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.param] (https://eel.is/c++draft/temp.param), [temp.arg.nontype] (https://eel.is/c++draft/temp.arg.nontype), [temp.type] (https://eel.is/c++draft/temp.type), [expr.const] (https://eel.is/c++draft/expr.const), [dcl.type.auto.deduct] (https://eel.is/c++draft/dcl.type.auto.deduct), [expr.prim.lambda.closure] (https://eel.is/c++draft/expr.prim.lambda.closure)
- **cppreference links:** [Template parameters and template arguments](https://en.cppreference.com/w/cpp/language/template_parameters), [Constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression), [Lambda expressions](https://en.cppreference.com/w/cpp/language/lambda)
- **Prerequisites:** template-instantiation-and-specialization, constant-expressions, template-argument-deduction, class-template-argument-deduction

## The one idea

A non-type template parameter, or NTTP, puts a value into a type. `std::array<int, 3>` and `std::array<int, 4>` are different types because `3` and `4` are different values, and the program needs to agree, in every translation unit, on whether two template argument lists name the same specialization. That question is called template-argument equivalence.

Almost every rule about NTTPs exists to keep that question answerable at compile time, without running user code: which types are allowed, which arguments are acceptable, and why the parameter of class type behaves like an object while the parameter of `int` type does not.

> **Mental model.** An NTTP value is part of the mangled name. If the compiler could not write the value down and compare it member by member, the type is not allowed.

## Which types are allowed, by version

| Standard | Adds |
| --- | --- |
| C++98 | integral and enumeration types, pointers to objects and functions, lvalue references to objects and functions, pointers to members |
| C++11 | `std::nullptr_t` |
| C++17 | placeholder types: `auto` and `decltype(auto)` |
| C++20 | floating-point types and structural literal class types, plus arrays of these inside classes |

The parameter's declared type is adjusted like a function parameter's. An array type becomes a pointer, a function type becomes a pointer to function, and top-level cv-qualifiers are dropped, so `template<const int N>` declares a parameter of type `int`.

C++20 defines a **structural type** as a scalar type, an lvalue reference type, or a literal class type whose bases and non-static data members are all public and non-mutable, and whose base and member types are themselves structural or arrays of structural types. User-provided constructors are allowed, as long as the class is literal. The standard does not promise that library types are structural. In practice GCC and Clang accept `std::array` and `std::pair` of structural types, and reject `std::string` and `std::string_view`, whose members are private.

```cpp
#include <string>

struct Point { int x, y; };                 // structural
class Hidden { int v = 0; public: constexpr Hidden() = default; };
struct Cache { mutable int hits; };

template<Point P> struct A {};              // OK since C++20
template<double D> struct B {};             // OK since C++20
// template<Hidden H> struct C {};          // error: private member
// template<Cache K> struct E {};           // error: mutable member
// template<std::string S> struct F {};     // error: not structural
```

> **Standardese.** [temp.param] lists the permitted types: a structural type, a type containing a placeholder, or a placeholder for a deduced class type. The definition of structural type in the same section is what C++20 compilers check, and GCC and Clang both report "not a structural type" when it fails.

## Arguments are converted constant expressions

An argument for an NTTP of non-reference type must be a converted constant expression of the parameter's type, as defined in [expr.const]. Only a short list of conversions is allowed: integral promotions and integral conversions that are not narrowing, floating-point promotions and exact floating-point conversions, array-to-pointer and function-to-pointer conversions, qualification conversions, null pointer conversions from `std::nullptr_t`, and user-defined conversions built from these.

Two consequences surprise people. Narrowing is an error, even when the value would fit after wrapping. And an integer argument for a `double` parameter is rejected, because the integral-to-floating conversion is not on the list.

```cpp
template<unsigned char C> struct Byte {};
template<double D> struct Scale {};

Byte<200> ok;
// Byte<300> bad;     // error: narrowing conversion of 300
Scale<1.0> fine;
// Scale<1> no;       // error: int to double is not allowed here
```

For a class-type parameter, the argument copy-initializes the parameter, so a constexpr converting constructor works: given `struct Q { int v; constexpr Q(int x) : v(x) {} };`, writing `X<5>` for `template<Q P> struct X` is fine.

## Pointer and reference arguments

Before C++17, an argument for a pointer or reference parameter had to be spelled as the address of, or the name of, an object or function with linkage. C++17 relaxed that to any constant expression, then listed what the pointer or reference may not designate: a temporary, a string literal, the result of `typeid`, the predefined `__func__` variable, and, in C++17 only, any subobject. C++20 allows subobjects, so `&arr[1]` and `&obj.member` became valid arguments, while subobjects of the forbidden objects remain forbidden.

```cpp
template<const char* P> struct Tag {};
template<int* P> struct Slot {};
int arr[3];

// Tag<"hi"> t1;           // error: string literal
constexpr char name[] = "hi";
Tag<name> t2;              // OK: names an object with static storage
Slot<&arr[1]> s;           // OK since C++20; an error in C++17

void f() {
  static constexpr char local[] = "hi";
  Tag<local> t3;           // OK since C++17; C++14 required linkage
  (void)t3;
}
```

> **Pitfall.** A string literal is rejected because two identical literals need not be the same object, so `Tag<"hi">` in two places could not be guaranteed to name one type. The usual way to pass text is a class-type NTTP that holds the characters by value, shown below.

A reference parameter cannot bind to a temporary either, so `template<const int& R>` does not accept `X<42>`.

## auto parameters

C++17 lets a parameter be declared with a placeholder. `template<auto V>` deduces the parameter's type from the argument, as if by `auto x = argument;`, and `template<decltype(auto) V>` deduces it as `decltype` would, which can make it a reference. A pack `template<auto... Vs>` may hold values of different types.

The deduced type is part of the identity. `X<1>` and `X<1u>` are different specializations because their parameters have different types, even though the values compare equal.

```cpp
#include <type_traits>

template<auto V> struct X {};
template<auto... Vs> struct List {};

static_assert(!std::is_same_v<X<1>, X<1u>>);   // int versus unsigned
static_assert(std::is_same_v<X<1>, X<2 - 1>>); // same type, same value
List<1, 'c', true> mixed;                       // int, char, bool
```

Since C++20 a placeholder also accepts class values. `template<auto V>` given `Point{1, 2}` deduces `Point`, provided the deduced type is structural; if it is not, the program is ill-formed.

## Template-argument equivalence

[temp.type] decides when two specializations are the same. Two values of an NTTP are template-argument-equivalent when they have the same type and integral values compare equal, floating-point values are identical, pointers have the same pointer value, pointers to members refer to the same member or are both null, references refer to the same entity, and class values have equivalent subobjects and reference members, recursively.

"Identical" is deliberate for floating point: it is not `==`. Positive and negative zero compare equal but are different values, so they produce different types.

```cpp
#include <type_traits>

template<double D> struct F {};

static_assert(!std::is_same_v<F<0.0>, F<-0.0>>);  // distinct specializations
static_assert(std::is_same_v<F<0.5>, F<1.0 / 2>>); // same value, same type
```

Pointers compare by address, not by what they point to. Two distinct arrays holding the same characters give two different specializations, because the identity of the object is the value. Class-type parameters work the other way round and compare their contents, which is exactly why a wrapper that stores characters by value can do what a `const char*` parameter cannot.

## Class-type parameters and template parameter objects

Inside the template, an NTTP of scalar type is a prvalue, so you cannot take its address. An NTTP of class type is different: its name denotes a **template parameter object**, an object of type `const T` with static storage duration. There is exactly one such object for each distinct value across the whole program, so every specialization with an equivalent argument shares it, and a reference to it never dangles.

```cpp
#include <cstdio>

struct P { int x; };
template<P V> const P& get() { return V; }   // fine: V lives for the whole program
// template<int N> const int* addr() { return &N; }  // error: N is a prvalue

int main() {
  std::printf("%d %d\n", &get<P{1}>() == &get<P{1}>(),  // 1: one object
                         &get<P{1}>() == &get<P{2}>()); // 0
}
```

This is what makes string-literal wrappers work. A small class holds a character array, and a constructor taking a reference to an array lets class template argument deduction work out its size. The parameter is declared with the class template name alone, a placeholder for a deduced class type, which C++20 allows.

```cpp
#include <cstddef>
#include <cstdio>

template<std::size_t N> struct fixed_string {
  char data[N];
  constexpr fixed_string(const char (&s)[N]) {
    for (std::size_t i = 0; i < N; ++i) data[i] = s[i];
  }
};

template<fixed_string S> struct Name {
  static constexpr const char* get() { return S.data; }
};

int main() { std::puts(Name<"hello">::get()); }  // prints hello
```

Two `Name<"hello">` written in different files are the same type, because the arguments are compared character by character rather than by address.

### Lambdas as arguments

C++20 also allows lambda expressions to appear in template arguments. A capture-less lambda's closure type has no data members, and CWG 2845 clarified that such a closure type is structural, so it can be the argument of an `auto` parameter and called inside the template. Every lambda expression has a unique closure type, so two textually identical lambdas give two different specializations.

```cpp
template<auto F> int call() { return F(); }

int seven = call<[] { return 7; }>();  // OK since C++20
```

## What to remember

- An NTTP value is part of the type, so its type must allow comparison at compile time: that is the structural-type rule.
- C++11 added `nullptr_t`, C++17 added `auto` and `decltype(auto)`, and C++20 added floating-point and structural class types.
- Structural classes have only public, non-mutable members and bases of structural type; `std::string` and `std::string_view` are rejected in practice.
- Arguments are converted constant expressions: narrowing is ill-formed, and `int` to `double` is not allowed.
- Pointer and reference arguments cannot designate string literals, temporaries, `typeid` results or `__func__`; subobjects are allowed only since C++20.
- `X<1>` and `X<1u>` differ for an `auto` parameter, and `0.0` and `-0.0` differ for a `double` parameter.
- A class-type NTTP names a single `const` template parameter object with static storage duration, shared by all equivalent arguments.
- Scalar NTTPs are prvalues; you cannot take their address.
- Text goes in as a `fixed_string`-style class, not as `const char*`.

## Concept Map Outline

- **Non-type template parameters:** Compile-time values that become part of a specialization's identity.
  - **Allowed types:** The set grew from integers and addresses to floating point and classes.
    - **C++98 and C++11:** Integral, enumeration, object and function pointers, lvalue references, member pointers, nullptr_t.
    - **C++20 additions:** Floating-point types and structural literal class types.
    - **Structural class:** Literal, with all bases and non-static members public, non-mutable and structural.
    - **Type adjustments:** Arrays and functions decay to pointers and top-level cv is dropped.
  - **Acceptable arguments:** Each argument must be a converted constant expression of the parameter type.
    - **No narrowing:** Byte<300> for an unsigned char parameter is ill-formed.
    - **No int to double:** Floating-integral conversions are not allowed, so Scale<1> fails for a double parameter.
    - **Class arguments:** A class parameter is copy-initialized, so constexpr converting constructors work.
  - **Pointers and references:** What an address argument may designate changed in C++17 and C++20.
    - **Before C++17:** Only the address or name of a complete object or function with linkage.
    - **Never allowed:** String literals, temporaries, typeid results and __func__.
    - **Subobjects:** Array elements and members became valid arguments in C++20.
  - **auto parameters:** C++17 placeholders deduce the parameter type from the argument.
    - **Type is identity:** X<1> and X<1u> are different specializations.
    - **decltype(auto):** Deduces like decltype, so a parenthesized name can give a reference parameter.
    - **Heterogeneous packs:** template<auto... Vs> can hold values of different types.
  - **Argument equivalence:** [temp.type] decides when two argument lists name the same specialization.
    - **Same type required:** Values must have the same type before they are compared.
    - **Floating point identical:** Identical, not ==, so 0.0 and -0.0 give different specializations.
    - **Classes member-wise:** Class values are equivalent when their subobjects are, recursively.
  - **Template parameter objects:** How class-type parameters exist at run time.
    - **One static object:** A class NTTP names a const object with static storage duration, one per value.
    - **Scalars are prvalues:** &N is ill-formed for template<int N>.
    - **fixed_string idiom:** A class holding a char array, deduced by CTAD, carries text as an argument.
    - **Lambda arguments:** C++20 allows capture-less lambdas as arguments; each lambda is a distinct value.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.type], [temp.param], [dcl.type.auto.deduct])

What are the values of `A` and `B`?

```cpp
#include <type_traits>

template<auto V> struct X {};

constexpr bool A = std::is_same_v<X<1>, X<2 - 1>>;
constexpr bool B = std::is_same_v<X<1>, X<1u>>;
```

A. Both are true
B. `A` is true, `B` is false
C. `A` is false, `B` is false
D. Ill-formed: `auto` cannot be the type of a template parameter

**Answer (B):** `A` is true, `B` is false

**Why:** `2 - 1` is the `int` value 1, so `A` names the same specialization twice. For `X<1u>` the placeholder deduces `unsigned int`, and template-argument equivalence requires the same type as well as the same value, so `B` is false. `auto` parameters have been allowed since C++17.

### Question 2 [warmup] ([temp.arg.nontype])

Which line is ill-formed in C++23?

```cpp
template<const char* P> struct Tag {};

constexpr char name[] = "hi";

Tag<name> a;      // #1
Tag<"hi"> b;      // #2
Tag<nullptr> c;   // #3
```

A. #1, because `name` has internal linkage
B. #3, because a null pointer is not an object address
C. None of them since C++17
D. #2, because a pointer argument cannot designate a string literal

**Answer (D):** #2, because a pointer argument cannot designate a string literal

**Why:** [temp.arg.nontype] forbids a pointer or reference argument from referring to a string literal, a temporary, a `typeid` result or `__func__`, so #2 is ill-formed. Internal linkage has been enough since C++11 and no linkage is needed since C++17, so #1 is fine, and a null pointer value is a valid argument for a pointer parameter. Pass text through a class-type parameter that stores the characters instead.

### Question 3 [warmup] ([temp.param], [temp.arg.nontype], [over.match.class.deduct])

In C++20, what does this program print?

```cpp
#include <cstddef>
#include <cstdio>

template<std::size_t N> struct fixed_string {
  char data[N];
  constexpr fixed_string(const char (&s)[N]) {
    for (std::size_t i = 0; i < N; ++i) data[i] = s[i];
  }
};

template<fixed_string S> struct Name {
  static constexpr const char* get() { return S.data; }
};

int main() { std::puts(Name<"ok">::get()); }
```

A. `ok`
B. Nothing: ill-formed because string literals cannot be template arguments
C. Nothing: ill-formed because `fixed_string` has a user-provided constructor
D. Undefined behavior: `S.data` dangles after `get` returns

**Answer (A):** `ok`

**Why:** The parameter is a placeholder for a deduced class type, so `fixed_string<3>` is deduced from `"ok"` and the class copies the characters. The string-literal ban applies to pointer and reference arguments, not to a class value built from a literal, and user-provided constructors are fine in a structural type. `S` names a template parameter object with static storage duration, so the returned pointer stays valid.

### Question 4 [tricky] ([temp.type], [temp.param])

In C++20, on an implementation with IEEE 754 `double` (such as any x86-64 or arm64 target), what is the value of `same`?

```cpp
#include <type_traits>

template<double D> struct F {};

constexpr bool same = std::is_same_v<F<0.0>, F<-0.0>>;
```

A. `true`, because `0.0 == -0.0`
B. `false`
C. Ill-formed: floating-point types cannot be template parameters
D. Unspecified

**Answer (B):** `false`

**Why:** For floating-point arguments, [temp.type] requires the values to be identical, not merely equal under `==`. Positive and negative zero compare equal but are different values, so they give two distinct specializations. Floating-point parameters are allowed since C++20, so the third option describes C++17.

### Question 5 [tricky] ([expr.const], [temp.arg.nontype])

In C++20, is this well-formed?

```cpp
template<double D> struct Scale {};

Scale<1> s;
```

A. Well-formed: 1 converts exactly to 1.0
B. Ill-formed: integral-to-floating conversions are not allowed in a converted constant expression
C. Well-formed, but `Scale<1>` and `Scale<1.0>` are different types
D. Ill-formed: floating-point parameters require a floating-point literal with a suffix

**Answer (B):** Ill-formed: integral-to-floating conversions are not allowed in a converted constant expression

**Why:** An NTTP argument must be a converted constant expression of the parameter type, and [expr.const] allows only a short list of conversions: non-narrowing integral conversions and promotions, floating-point promotions and exact floating-point conversions, and a few pointer conversions. A floating-integral conversion is not on the list, even though 1 is exactly representable, so the program is ill-formed. GCC and Clang both reject it; write `Scale<1.0>`.

### Question 6 [tricky] ([temp.param], [temp.type])

In C++20, what does this program print?

```cpp
#include <cstdio>

struct P { int x; };

template<P V> const P* f() { return &V; }
template<P V> const P* g() { return &V; }

int main() {
  std::printf("%d\n", f<P{1}>() == g<P{1}>());
}
```

A. `0`: each function template has its own copy of the argument
B. Ill-formed: a template parameter is a prvalue and has no address
C. Undefined behavior: the pointer dangles after `where` returns
D. `1`

**Answer (D):** `1`

**Why:** A class-type NTTP names a template parameter object of type `const P` with static storage duration, and no two such objects are template-argument-equivalent, so `f<P{1}>` and `g<P{1}>` both refer to the one object for the value `P{1}`. Taking the address is fine because, unlike a scalar NTTP, the name is an lvalue. The prvalue rule in the second option applies to `template<int N>`, where `&N` is ill-formed.

### Question 7 [standardese] ([temp.param], [basic.types.general])

Under C++20 rules, which of these class types can be the type of a non-type template parameter?

```cpp
struct A { int v; constexpr A(int x) : v(x) {} };
class B { int v = 0; public: constexpr B() = default; };
struct C { mutable int v; };
struct D : private A { constexpr D() : A(0) {} };
```

A. Only `A`
B. `A` and `B`
C. `A` and `D`
D. All four, since each is a literal type

**Answer (A):** Only `A`

**Why:** A structural class type must be a literal class whose bases and non-static data members are all public and non-mutable, with structural types. `A` qualifies; its user-provided constexpr constructor does not matter. `B` has a private member, `C` a mutable one, and `D` a private base, so none of them is structural even though all are literal types.

### Question 8 [standardese] ([temp.arg.nontype])

In which standard versions is `Slot<&arr[1]>` a valid template argument?

```cpp
template<int* P> struct Slot {};
int arr[3];

Slot<&arr[1]> s;
```

A. C++20 and later
B. C++17 and later
C. C++11 and later
D. None: array elements can never be template arguments

**Answer (A):** C++20 and later

**Why:** Before C++17 a pointer argument had to be the address of a complete object with linkage, which an array element is not. C++17 accepted any constant expression but still excluded pointers to subobjects. C++20 lifted that exclusion, keeping only the bans on temporaries, string literals, `typeid` results, `__func__` and their subobjects, so the argument is valid from C++20 on.
