# Type traits and metaprogramming

> A type trait is a class template that maps types to a constant or to another type, answered either by specialization or by the compiler itself. Knowing exactly which question each trait asks, and when its operands are instantiated, separates working metaprograms from subtly wrong ones.

- **Source:** C++ Atlas (https://cppatlas.com/topics/type-traits-and-metaprogramming)
- **Track:** Templates
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [meta.rqmts] (https://eel.is/c++draft/meta.rqmts), [meta.type.synop] (https://eel.is/c++draft/meta.type.synop), [meta.help] (https://eel.is/c++draft/meta.help), [meta.unary.prop] (https://eel.is/c++draft/meta.unary.prop), [meta.rel] (https://eel.is/c++draft/meta.rel), [meta.trans.other] (https://eel.is/c++draft/meta.trans.other), [meta.logical] (https://eel.is/c++draft/meta.logical), [declval] (https://eel.is/c++draft/declval), [stmt.if] (https://eel.is/c++draft/stmt.if), [expr.context] (https://eel.is/c++draft/expr.context), [dcl.pre] (https://eel.is/c++draft/dcl.pre)
- **cppreference links:** [Metaprogramming library](https://en.cppreference.com/w/cpp/meta), [std::integral_constant](https://en.cppreference.com/w/cpp/types/integral_constant), [std::is_trivially_copyable](https://en.cppreference.com/w/cpp/types/is_trivially_copyable), [std::is_constructible](https://en.cppreference.com/w/cpp/types/is_constructible), [std::is_convertible](https://en.cppreference.com/w/cpp/types/is_convertible), [std::decay](https://en.cppreference.com/w/cpp/types/decay), [std::common_type](https://en.cppreference.com/w/cpp/types/common_type), [std::conjunction](https://en.cppreference.com/w/cpp/types/conjunction), [std::declval](https://en.cppreference.com/w/cpp/utility/declval), [if statement (constexpr if)](https://en.cppreference.com/w/cpp/language/if)
- **Prerequisites:** template-instantiation-and-specialization, type-deduction-auto-decltype, sfinae

## The one idea

A type trait is a function evaluated by the compiler. Its argument is a type, and its result is either a constant, such as `std::is_integral<T>::value`, or another type, such as `std::remove_reference<T>::type`. The function is written as a class template, and its "body" is the set of specializations the compiler picks from, or, for the traits that cannot be written in C++, a built-in the compiler answers directly.

Two habits make traits reliable. First, read the precise question a trait asks, because many names promise more or less than they test. Second, know when an operand gets instantiated, because metaprograms fail most often by instantiating something that was never meant to be looked at.

> **Mental model.** A trait is a lookup table indexed by type. Specializations are the rows, `true_type` and `false_type` are the cells, and the compiler fills in the rows nobody could write by hand.

## How a trait is built

The building block is `std::integral_constant<T, v>`, which holds `static constexpr T value = v`, a `type` alias to itself, and conversions to `T` so it can be used directly as a value. `std::true_type` and `std::false_type` are its `bool` instances. A predicate trait derives from one of them, so the answer travels by inheritance and can be dispatched on as a type.

```cpp
#include <type_traits>

template<class T> struct is_ptr : std::false_type {};      // primary: the default row
template<class T> struct is_ptr<T*> : std::true_type {};   // partial specialization
template<class T> struct is_ptr<T* const> : std::true_type {};

template<class T> inline constexpr bool is_ptr_v = is_ptr<T>::value;

static_assert(is_ptr_v<int* const> && !is_ptr_v<int>);
```

C++14 added the `_t` alias templates, so `std::remove_reference_t<T>` replaces `typename std::remove_reference<T>::type`. C++17 added the `_v` variable templates. They are pure conveniences; the class template is still what gets instantiated and what you inherit from when composing traits.

Cv-qualifiers and references interact in a way that trips everyone once. A reference type is never const, because `const` applies to the referred-to type, so `is_const_v<const int&>` is false and `remove_const_t<const int&>` is `const int&` unchanged. Strip the reference first.

```cpp
#include <type_traits>

static_assert(!std::is_const_v<const int&>);
static_assert(std::is_same_v<std::remove_const_t<const int&>, const int&>);
static_assert(std::is_same_v<std::remove_cvref_t<const int&>, int>);
```

## The families and the surprising members

The standard groups traits into primary type categories such as `is_class` and `is_pointer`, composite categories such as `is_arithmetic` and `is_object`, type properties such as `is_trivially_copyable` and `is_constructible`, relationships such as `is_same`, `is_base_of` and `is_convertible`, and transformations such as `decay` and `common_type`. Exactly one primary category is true for any type. The trouble lives in the properties and relationships.

### Trivially copyable is not trivial

`is_trivially_copyable` asks whether the type can be copied with `memcpy`: every eligible copy and move operation is trivial, at least one of them is not deleted, and the destructor is trivial and not deleted. `is_trivial` additionally requires trivial default constructors. A class with a user-provided default constructor is therefore trivially copyable but not trivial. For copying bytes, `is_trivially_copyable` is the trait you want; C++26 deprecates `is_trivial` precisely because it mixes two unrelated questions.

```cpp
#include <type_traits>

struct Init { Init() {} int x; };  // user-provided default constructor
static_assert(std::is_trivially_copyable_v<Init>);  // memcpy is fine
static_assert(!std::is_trivial_v<Init>);
```

### Constructible versus convertible

`is_constructible<T, Args...>` asks whether the variable definition `T t(std::declval<Args>()...);` is well-formed. That is direct-initialization, so explicit constructors count, narrowing is allowed, and, since C++20, parenthesized aggregate initialization counts too. `is_convertible<From, To>` asks whether a function returning `To` could `return std::declval<From>();`, which is copy-initialization, so explicit constructors do not count. Only the immediate context is checked: if the chosen constructor's body would fail to compile, the trait still says true.

```cpp
#include <type_traits>

struct Id { explicit Id(int); };
struct Pair { int a, b; };

static_assert(std::is_constructible_v<Id, int>);       // Id t(0) is fine
static_assert(!std::is_convertible_v<int, Id>);        // Id f() { return 0; } is not
static_assert(std::is_constructible_v<int, double>);   // narrowing allowed with parens
static_assert(std::is_constructible_v<Pair, int, int>); // C++20 Pair(1, 2)
static_assert(std::is_constructible_v<const int&, long>); // binds to a temporary
static_assert(!std::is_constructible_v<int&, long>);
```

### decay, remove_cvref and common_type

`decay_t<T>` applies what passing by value does: it removes the reference, then turns arrays into pointers to their element type, functions into function pointers, and strips top-level cv from everything else. `remove_cvref_t<T>`, added in C++20, only removes the reference and the cv-qualifiers, so arrays stay arrays. Reach for `remove_cvref_t` when you want the "plain" type, and `decay_t` only when you are modelling a by-value copy.

`common_type_t<T, U>` is, roughly, the decayed type of `false ? declval<T>() : declval<U>()`. It follows the usual arithmetic conversions, so `common_type_t<int, unsigned>` is `unsigned` and `common_type_t<char, short>` is `int`, and it always yields a non-reference type.

```cpp
#include <type_traits>

static_assert(std::is_same_v<std::decay_t<const int[3]>, const int*>);
static_assert(std::is_same_v<std::decay_t<int(int)>, int (*)(int)>);
static_assert(std::is_same_v<std::remove_cvref_t<const int (&)[3]>, int[3]>);
static_assert(std::is_same_v<std::common_type_t<const int&, int&>, int>);
static_assert(std::is_same_v<std::common_type_t<int, unsigned>, unsigned>);
```

## Traits the compiler must answer

Some questions cannot be answered by any specialization. Nothing in the language distinguishes a union from a class, detects a trivial copy constructor, tells whether a class is an aggregate or is final, or names an enumeration's underlying type. The standard library implements `is_union`, `is_trivially_copyable`, `is_standard_layout`, `is_aggregate`, `is_final`, `has_virtual_destructor`, `underlying_type` and others with compiler built-ins such as `__is_union(T)`. Many traits also require complete types; asking `is_trivially_copyable` about an incomplete class is undefined behaviour, which is a further reason to treat traits as compiler queries rather than ordinary templates.

Because the library may implement any trait with magic, you are not allowed to add rows to the table.

> **Standardese.** [meta.type.synop] says the behaviour of a program that adds specializations for any of the templates in the type traits subclause is undefined unless otherwise specified. The exceptions are `common_type`, which may be specialized when at least one argument is a program-defined type, and `basic_common_reference` since C++20.

```cpp
#include <type_traits>

struct Fixed {};
// template<> struct std::is_integral<Fixed> : std::true_type {};
// undefined behavior; GCC with libstdc++ accepts it silently,
// while Clang with libc++ rejects it as an invalid specialization
```

Write your own trait, such as `is_my_integral`, instead.

## Unevaluated operands and std::declval

Metaprograms constantly ask "what would this expression be?" without running it. The operands of `sizeof`, `decltype`, `noexcept`, a non-polymorphic `typeid` and `requires` expressions are unevaluated, as described in [expr.context]: they are type-checked but never executed, and functions named inside them are not odr-used.

`std::declval<T>()` is a function declared to return `add_rvalue_reference_t<T>`, so `declval<int>()` is an `int&&` xvalue and `declval<int&>()` is an `int&` lvalue. It conjures a value of any type, even one with no usable constructor. It only works in unevaluated operands: [declval] makes odr-use ill-formed, and both libstdc++ and libc++ enforce that with a `static_assert` in its definition.

```cpp
#include <type_traits>
#include <utility>

struct NoDefault { NoDefault(int); double size() const; };

using R = decltype(std::declval<const NoDefault&>().size());  // double, nothing runs
static_assert(std::is_same_v<R, double>);

// int bad = std::declval<int>();  // ill-formed: odr-use of declval
```

## if constexpr and discarded statements

C++17's `if constexpr` evaluates its condition as a constant expression and discards the branch not taken. Inside a template, a discarded statement is not instantiated, so it can contain code that would be invalid for the current arguments. In any function, `return` statements in a discarded branch do not take part in return type deduction, and an entity odr-used only in a discarded branch needs no definition.

Outside a template nothing is instantiated, so a discarded branch is checked like any other code: it must name declared entities and be otherwise well-formed.

```cpp
#include <type_traits>

template<class T> int to_int(T t) {
  if constexpr (std::is_pointer_v<T>) return *t;  // not instantiated for int
  else if constexpr (std::is_integral_v<T>) return t;
  else static_assert(false, "unsupported type");  // OK since C++23
}
int a = to_int(1);
```

That trailing `static_assert(false)` was ill-formed, no diagnostic required, before P2593. C++23 changed [dcl.pre] so that a `static_assert` inside a template definition is only evaluated on instantiation, and GCC 13 and Clang 17 apply the change in earlier modes too.

> **Pitfall.** `if constexpr` is not the preprocessor. In a non-template function, `if constexpr (false) { undeclared(); }` is ill-formed, and `static_assert(false)` in a discarded branch still fires, because the function is not a template definition.

## conjunction, disjunction and lazy instantiation

`std::conjunction<B...>`, `disjunction` and `negation` arrived in C++17. They are not just spelled-out `&&` and `||`. `conjunction` derives from the first `Bi` whose `value` is false, or from the last one, and it stops: later arguments are never asked for their `::value`, so they are never instantiated. A fold expression such as `(Ts::value && ...)` names every `Ts::value`, and naming a member of a class template specialization instantiates it, before `&&` gets a chance to short-circuit.

```cpp
#include <type_traits>

template<class T> struct Expensive {
  static_assert(sizeof(T) == 0, "must not be instantiated");
  static constexpr bool value = true;
};

static_assert(!std::conjunction_v<std::is_integral<float>, Expensive<int>>);  // OK
// template<class... Ts> constexpr bool all = (Ts::value && ...);
// static_assert(!all<std::is_integral<float>, Expensive<int>>);  // static_assert fires
```

This matters for recursive traits and for traits guarding operations that are hard errors on some types. Note also that a conjunction's result type is one of its arguments, not a fresh `bool_constant`, so it carries that argument's `value_type`.

## What to remember

- A trait is a class template whose specializations, or a compiler built-in, map types to `integral_constant` values or to types; `_t` is C++14 and `_v` is C++17.
- References are never const: `is_const_v<const int&>` is false and `remove_const` leaves it alone.
- `is_trivially_copyable` answers "can I memcpy it"; `is_trivial` also demands trivial default construction and is deprecated in C++26.
- `is_constructible` tests direct-initialization, explicit constructors included; `is_convertible` tests implicit conversion; both check only the immediate context.
- `decay_t` models pass-by-value; `remove_cvref_t` keeps arrays and functions intact; `common_type_t` follows the conditional operator and always decays.
- Specializing a standard trait is undefined behaviour, except `common_type` and `basic_common_reference` for program-defined types.
- `std::declval` is for unevaluated operands only; odr-using it is ill-formed.
- `if constexpr` discards without instantiating only inside templates; in C++23 `static_assert(false)` in such a branch is fine.
- `conjunction` and `disjunction` short-circuit instantiation; a fold over `::value` does not.

## Concept Map Outline

- **Type traits:** Class templates the compiler evaluates to map types to constants or to other types.
  - **How traits are built:** A primary template gives the default answer and specializations add the exceptions.
    - **integral_constant:** Holds a static constexpr value; true_type and false_type are its bool instances.
    - **_t and _v helpers:** Alias templates arrived in C++14 and variable templates in C++17; both are conveniences.
    - **References are never const:** is_const_v<const int&> is false, and remove_const leaves a reference unchanged.
  - **Surprising properties:** Several trait names promise more or less than the question they actually ask.
    - **Trivially copyable:** Asks whether memcpy is valid; a user-provided default constructor does not matter.
    - **is_trivial:** Also requires trivial default construction; deprecated in C++26.
    - **is_constructible:** Tests direct-initialization T t(args...), so explicit constructors and narrowing count.
    - **is_convertible:** Tests copy-initialization through a return statement, so explicit constructors do not count.
  - **Transformations:** Traits whose result is a type, read through the _t alias.
    - **decay:** Models pass-by-value: drops references and cv, turns arrays and functions into pointers.
    - **remove_cvref:** C++20; strips only references and cv, so arrays stay arrays.
    - **common_type:** Decayed type of the conditional operator; int and unsigned give unsigned.
  - **Compiler-backed traits:** Questions no specialization can answer are implemented with built-ins.
    - **Built-in intrinsics:** is_union, is_aggregate, is_final and underlying_type need compiler support.
    - **Specializing is UB:** Adding specializations of standard traits is undefined behavior unless explicitly permitted.
    - **Permitted exceptions:** common_type and, since C++20, basic_common_reference may be specialized for program-defined types.
  - **Unevaluated contexts:** Operands that are type-checked but never executed or odr-used.
    - **The operators:** sizeof, decltype, noexcept, non-polymorphic typeid and requires expressions.
    - **std::declval:** Returns add_rvalue_reference_t<T>; odr-using it is ill-formed.
  - **Control at compile time:** Choosing code paths and combining predicates without unwanted instantiation.
    - **if constexpr:** C++17; a discarded branch is not instantiated, but only inside a template.
    - **static_assert(false):** Fine in a discarded template branch since C++23 (P2593); still fires in non-templates.
    - **conjunction:** Stops at the first false argument and never instantiates the rest; a fold over ::value does.

## Standardese Quiz Questions

### Question 1 [warmup] ([meta.unary.prop], [dcl.ref])

Which of these `static_assert`s fails?

```cpp
#include <type_traits>

static_assert(std::is_const_v<const int>);                                   // #1
static_assert(std::is_const_v<const int&>);                                  // #2
static_assert(std::is_same_v<std::remove_cvref_t<const int&>, int>);         // #3
static_assert(std::is_same_v<std::remove_reference_t<const int&>, const int>); // #4
```

A. #1
B. #3
C. #2
D. #4
E. None of them

**Answer (C):** #2

**Why:** A reference type is never cv-qualified: the `const` in `const int&` belongs to the referred-to type, so `is_const_v<const int&>` is false, so #2 fails and makes the program ill-formed. The same reasoning means `remove_const_t<const int&>` is unchanged. #3 and #4 hold because they remove the reference first, which is why `remove_cvref_t` exists.

### Question 2 [warmup] ([meta.unary.prop], [meta.rel], [dcl.init.general])

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

```cpp
#include <type_traits>

struct Id { explicit Id(int); };

constexpr bool A = std::is_constructible_v<Id, int>;
constexpr bool B = std::is_convertible_v<int, Id>;
```

A. `A` is true, `B` is true
B. `A` is false, `B` is false
C. `A` is false, `B` is true
D. `A` is true, `B` is false

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

**Why:** `is_constructible<Id, int>` asks whether `Id t(std::declval<int>());` is well-formed, which is direct-initialization, so the explicit constructor is usable and `A` is true. `is_convertible<int, Id>` asks whether a function returning `Id` can `return` an `int`, which is copy-initialization and ignores explicit constructors, so `B` is false. Treating the two traits as synonyms is the usual mistake.

### Question 3 [warmup] ([meta.trans.other], [conv.array])

What type is `D`?

```cpp
#include <type_traits>

using D = std::decay_t<const int (&)[3]>;
```

A. `int*`
B. `const int*`
C. `int[3]`
D. `const int[3]`

**Answer (B):** `const int*`

**Why:** `decay` first removes the reference, leaving `const int[3]`, and then applies array-to-pointer conversion, giving a pointer to the element type `const int`. The `const` is not top-level on a pointer to const, so it survives. `int[3]` is what `remove_cvref_t` would give, since it keeps arrays as arrays.

### Question 4 [tricky] ([class.prop], [meta.unary.prop])

What are the values of `C` and `T`?

```cpp
#include <type_traits>

struct Init {
  Init() {}
  int x;
};

constexpr bool C = std::is_trivially_copyable_v<Init>;
constexpr bool T = std::is_trivial_v<Init>;
```

A. `C` is true, `T` is false
B. Both are true
C. Both are false
D. `C` is false, `T` is true

**Answer (A):** `C` is true, `T` is false

**Why:** Trivially copyable only looks at copy and move operations and the destructor, all of which are implicitly declared and trivial here, so `C` is true and `memcpy` is a valid way to copy an `Init`. A trivial class must also have a trivial default constructor, and `Init()` is user-provided, so `T` is false. A user-written constructor does not stop byte-wise copying.

### Question 5 [tricky] ([meta.logical], [temp.inst])

Which declaration makes the program ill-formed?

```cpp
#include <type_traits>

template<class T> struct Expensive {
  static_assert(sizeof(T) == 0, "must not be instantiated");
  static constexpr bool value = true;
};

template<class... Ts> constexpr bool all = (Ts::value && ...);

constexpr bool p = std::conjunction_v<std::is_integral<float>, Expensive<int>>; // #1
constexpr bool q = all<std::is_integral<float>, Expensive<int>>;              // #2
```

A. Neither: both short-circuit after `is_integral<float>`
B. Only #1
C. Both
D. Only #2

**Answer (D):** Only #2

**Why:** `conjunction` inherits from the first argument whose `value` is false and never asks later arguments for `::value`, so `Expensive<int>` is not instantiated in #1. The fold in #2 names `Expensive<int>::value`, and naming a member of a class template specialization instantiates the class, firing its `static_assert`, so #2 is ill-formed; the `&&` never gets a chance to short-circuit. Short-circuiting the evaluation is not the same as short-circuiting instantiation.

### Question 6 [tricky] ([stmt.if], [dcl.pre])

In C++23, which of these functions is well-formed?

```cpp
#include <type_traits>

void f() {
  if constexpr (sizeof(int) == 0) { static_assert(false); }
}

template<class T> void g() {
  if constexpr (sizeof(T) == 0) { static_assert(false); }
}
```

A. Both
B. Only `f`
C. Only `g`
D. Neither, because `static_assert(false)` is always ill-formed

**Answer (C):** Only `g`

**Why:** Discarding a branch of `if constexpr` only prevents instantiation, and only templates are instantiated. C++23 (P2593) changed `static_assert` so that inside a template definition it is evaluated on instantiation, which makes `g` fine. `f` is not a template, so its discarded branch is checked like ordinary code and the failing `static_assert` makes `f` ill-formed. The last option describes the rule before P2593, which compilers now apply retroactively.

### Question 7 [standardese] ([meta.type.synop], [namespace.std])

What does the C++23 standard say about this program?

```cpp
#include <type_traits>

struct Fixed {};

template<>
struct std::is_integral<Fixed> : std::true_type {};

int main() { return std::is_integral_v<Fixed>; }
```

A. It is well-formed and returns 1
B. Ill-formed: `is_integral` is declared `final`
C. Implementation-defined
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** [meta.type.synop] makes adding a specialization for any type trait template undefined behavior unless the trait's specification allows it, and only `common_type` and `basic_common_reference` do. Specializing a standard template for a program-defined type is allowed in general by [namespace.std], which makes the first option tempting, but the traits subclause overrides that. In practice GCC with libstdc++ accepts this, while Clang with libc++ rejects it.

### Question 8 [standardese] ([declval], [expr.context], [basic.def.odr])

Which use of `std::declval` is ill-formed?

```cpp
#include <utility>

struct NoDefault { NoDefault(int); int get() const; };

using A = decltype(std::declval<NoDefault>().get());       // #1
constexpr auto B = sizeof(std::declval<NoDefault>());      // #2
constexpr bool C = noexcept(std::declval<NoDefault>().get()); // #3
int D = std::declval<NoDefault>().get();                 // #4
```

A. #1, because `NoDefault` has no default constructor
B. #4 only
C. #2 and #4
D. None of them; `declval` merely returns an rvalue reference

**Answer (B):** #4 only

**Why:** The operands of `decltype`, `sizeof` and `noexcept` are unevaluated, so `declval` is not odr-used there and any type, constructible or not, is fine. #4 is an evaluated expression, which odr-uses `declval`, and [declval] makes that ill-formed; both libstdc++ and libc++ diagnose it with a `static_assert`. `sizeof` is a common doubt, but it is as unevaluated as `decltype`.
