Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::decay and std::decay_t — type transformation modeling pass-by-value

std::decay transforms a type at compile time to model pass-by-value. std::decay_t exposes the resulting type without writing ::type.

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

Syntax

#include <type_traits>
template<class T> struct decay;
template<class T> using decay_t = typename decay<T>::type; // in namespace std
using Result = std::decay_t<T>;

std::decay<T> from <type_traits> exposes its result as type; std::decay_t<T> aliases that result. It transforms a type, not an object, and performs no copy.

First let U = std::remove_reference_t<T>. For an array, the result is std::remove_extent_t<U>*; for a function, std::add_pointer_t<U>; otherwise, std::remove_cv_t<U>.

Only top-level qualifiers are removed, not pointee qualifiers. Multidimensional arrays lose only their first dimension. std::remove_cvref_t<T> does not convert array or function types to pointer types. std::decay_t<T> converts array types to pointer types, but does so for function types only when std::add_pointer_t<U> can form a pointer type. Cv- or ref-qualified function types such as void() const remain unchanged. A resulting pointer does not extend the pointed-to object's lifetime.

Examples

#include <type_traits>

using Function = int(double);

static_assert(std::is_same_v<typename std::decay<const int&>::type, int>);
static_assert(std::is_same_v<std::decay_t<const int(&)[3]>, const int*>);
static_assert(std::is_same_v<std::decay_t<Function&>, int(*)(double)>);
static_assert(std::is_same_v<std::decay_t<int[2][3]>, int(*)[3]>);
static_assert(std::is_same_v<std::decay_t<const int* const&>, const int*>);
static_assert(std::is_same_v<std::remove_cvref_t<int(&)[3]>, int[3]>);

int main() {}

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