CodeBlanks Logo Icon CodeBlanks

decay and remove_reference

Learn type transformation with decay and remove_reference.

decay and remove_reference

std::decay_t<T> strips references, const and arrays from a type and turns functions into pointers. std::decay_t<int&> becomes int, std::decay_t<const int&> becomes int, std::decay_t<int[5]> becomes int*.

std::remove_reference_t<T> strips only references; it keeps const and arrays. std::remove_reference_t<int&> becomes int but std::remove_reference_t<const int&> stays const int. These traits normalize template parameters.

Use in template parameters

When a template takes T&& as a universal reference, T may itself be a reference. To get the bare type use std::decay_t<T>. Example: template <typename T> struct Store { using value_type = std::decay_t<T>; }; makes Store<int&>::value_type equal to int.

The standard library applies decay in std::tuple, std::function and std::make_pair. This keeps the stored type reference-free even when the user calls with a reference. It is a standard pattern in template design.

Practice Write the CleanType template

Write template <typename T> struct CleanType with using type = std::decay_t<T>; inside. In main write std::cout << std::is_same_v<CleanType<int&>::type, int>;.

Starter code

main.cpp
#include <iostream>
#include <type_traits>

// Write the CleanType template

int main() {
    // Print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <type_traits>

template <typename T>
struct CleanType {
    using type = std::decay_t<T>;
};

int main() {
    std::cout << std::is_same_v<CleanType<int&>::type, int>;
    return 0;
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the remove_reference line

Question
template <typename T>
using Clean = std::____<T>;
Answer
template <typename T>
using Clean = std::remove_reference_t<T>;

Explanation: remove_reference_t<T> strips only references.

2 What does decay_t<int&> produce?

  • int Correct answer
  • int&
  • const int
  • int*

Explanation: decay_t strips references and const; the result is int.

3 Match each trait to its result

Term Meaning
decay_t<int&> int (decay)
decay_t<const int&> int (const dropped)
remove_reference_t<int&> int (ref only)
remove_reference_t<const int&> const int (ref dropped)

All lessons in Advanced