Home > Net >  inspecting 2D array inner type
inspecting 2D array inner type

Time:11-30

I am trying to check if the type of an array element is a specific type. See the following.

#include <type_traits>
#include <cstdint>
#include <iostream>

int main() {
    using arr = std::int32_t[2][2];

    std::cout << std::is_same_v<decltype(std::declval<arr>()[0][0]), std::int32_t> << std::endl;
}

>>> 0

Why is the above code printing zero? I also tried getting some other data about the type. See the following.

#include <type_traits>
#include <cstdint>
#include <iostream>
#include <typeinfo>

int main() {
    using arr = std::int32_t[2][2];

    std::cout << typeid(decltype(std::declval<arr>()[0][0])).name() << std::endl;
    std::cout << sizeof(decltype(std::declval<arr>()[0][0])) << std::endl;
}

>>> i
>>> 4

As can be seen above, the type is an integer and 4 bytes, just like an std::int32_t. What am I doing incorrectly? Am I misinterpreting the typeid output? Thanks.

I'm using g 12.1.0 compiling for c 17.

CodePudding user response:

The type of the expression is lvalue reference to std::int32_t. You can use remove_reference to get the expected std::int32_t:

#include <type_traits>
#include <cstdint>
#include <iostream>

int main() {
    using arr = std::int32_t[2][2];

    std::cout << std::is_same_v<decltype(std::declval<arr>()[0][0]), std::int32_t&&> << std::endl;
    std::cout << std::is_same_v<std::remove_reference_t<decltype(std::declval<arr>()[0][0])>, std::int32_t> << std::endl;
}

Live

Concerning your usage of typeid, first note that the name is implementation defined, it could be anything, you shouldnt assume that the name for int32_t is i (it is, but nevertheless ;).

Then (from cppreference on the typeid operator):

(1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the referenced type.

You are comparing two somewhat unrelated tools. typeid is to infer the type of an polymorphic object. For that usually reference or not does not matter, you just care about the dynamic type of the object. decltype on the other hand is to deduce the type of an expression where references do matter.

  •  Tags:  
  • c
  • Related