c++referenceintegral-type

Why a reference to an integer not considered an integral type?


Consider the following code snippet:

int x = 10;
std::cout << "Is Integral = " << std::is_integral_v<decltype(x)> << std::endl;
int & y = x;
std::cout << "Is Integral  = " << std::is_integral_v<decltype(y)> << std::endl;

Here x is considered an integral type but y is not.
Any explanation to why that is the case?


Solution

  • The definition of integral type from std::is_integral documentation:

    Checks whether T is an integral type. Provides the member constant value which is equal to true, if T is the type bool, char, char8_t(since C++20), char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants. Otherwise, value is equal to false.

    x's type is int - one of the types mentioned above.
    But y's type is int& ( a reference to int), not int. It is not one of the types for which std::is_integral returns true.

    If you want to check whether the type the reference is refering to is intergal, you can use std::remove_reference_t to "strip" the reference from the type:

    int x = 10;
    std::cout << "Is Integral = " << std::is_integral_v<decltype(x)> << std::endl;
    int& y = x;
    //--------------------------------------------------vvvvvvvvvvvvvvvvvvvvvvv---------------------------
    std::cout << "Is Integral = " << std::is_integral_v<std::remove_reference_t<decltype(y)>> << std::endl;
    

    Output:

    Is Integral = 1
    Is Integral = 1