【问题标题】:inspecting 2D array inner type检查二维数组内部类型
【发布时间】:2022-11-30 03:15:12
【问题描述】:

我正在尝试检查数组元素的类型是否为特定类型。请参阅以下内容。

#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

为什么上面的代码打印为零?我还尝试获取有关该类型的其他一些数据。请参阅以下内容。

#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

从上面可以看出,类型是一个整数和4个字节,就像一个std::int32_t。我做错了什么?我是否误解了 typeid 输出?谢谢。

我正在使用 g++ 12.1.0 为 c++ 17 编译。

【问题讨论】:

  • 为什么是 std::int32_t 而不是 int32_t
  • @tadman 我只是随机选择了一个惯例。
  • 这当然是随机的。
  • @tadman 当然。这当然也没有关系......特别是关于这个问题。
  • 我只是做一个观察,仅此而已。别管我。

标签: c++


【解决方案1】:

表达式的类型是对std::int32_t 的左值引用。您可以使用remove_reference 来获得预期的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

关于typeid 的使用,首先请注意name 是实现定义的,它可以是任何东西。然后(来自 typeid 运算符上的 cppreference

(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.

您正在比较两个有些不相关的工具。 typeid是推断多态对象的类型。对于那个通常参考与否并不重要。 decltype 推断出引用很重要的表达式的类型。

【讨论】:

  • 看到了谢谢typeid(...).name() 不应该返回 i&amp; 而不仅仅是 i 吗?
  • @Jaan 看到编辑,不
猜你喜欢
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多