【问题标题】:How do the type_info member functions work?type_info 成员函数是如何工作的?
【发布时间】:2020-02-05 10:50:10
【问题描述】:

我目前正在学习 Run-Time Type ID 和 Casting Operator。我有一些问题,你能帮我解决这个疑惑吗?

见以下代码:

 #include <iostream>
 #include <typeinfo>

 using namespace std;

 class base
 {

 };

 class derived
 {

 };

 int main()
 {
      cout<<typeid(char).name()<<endl;
      cout<<typeid(int).name()<<endl;
      cout<<typeid(float).name()<<endl;
      cout<<typeid(double).name()<<endl;
      cout<<typeid(base).name()<<endl;
      cout<<typeid(derived).name()<<endl;
 }

输出:

  c
  i
  f
  d
  4base
  7derived

  Process returned 0 (0x0)   execution time : 0.238 s
  Press any key to continue.

问题:

  1. typeid(base).name() 给出“4base”;这里4 是什么,typeid(derived).name() 给出“7derived”; 7 这里是什么?

  2. 为什么typeid(char).name() 和其他内置数据类型只给出第一个字母?

  3. type_info::before() 函数是什么?

感谢您的宝贵时间和回答。

【问题讨论】:

  • 名称由实现定义。如果他们愿意,他们可以归还小狗。如果您想要一个可读的名称,对于 gcc,请参阅 gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html 。
  • 乍一看,4 和 7 分别是 'base' 和 'derived' 的长度。如果您查看 Andrei 的链接,看起来这个长度前缀是 GCC 的修饰方案中字符串名称的分隔方式。
  • @AndreiDamian 虽然这是真的,但这并不能真正解释 为什么,这是一个非常有效的问题。
  • @KonradRudolph 答案是“因为他们可以”。

标签: c++


【解决方案1】:

type_info::name 返回实现定义的类型名称。它不一定与代码中这些类型名称的实际拼写相对应。

GCC 和 Clang 返回mangled names,因为这就是这些类型名称在内部的表示方式。您可以通过实施名称修饰规则手动对它们进行解构,也可以使用现有工具(例如 c++filt 或 the corresponding APIs)。

type_info::before 没有直接用处。它的值本质上是任意的,但一致。这使其可用于将type_info 对象存储在已排序的容器中,例如std::set,或将它们用作std::map 中的键。 std::type_info::before 在这里可以用作排序关系。或者,type_info 可能重载了operator &lt;,这可能是它应该做的。 Even standard library authors 不明白为什么没有这样做。

以下代码显示了一个示例,其中使用 type_info::before 曾经是必要的。从 C++11 开始,不再需要它,因为您可以改用 type_index 键。此外,这显然是对运行时类型信息的人为使用:在实际代码中你根本不会使用type_info,你会解决函数重载的问题。

#include <iostream>
#include <map>
#include <string>
#include <typeinfo>

auto type_info_less = [](std::type_info const* a, std::type_info const* b) {
    return a->before(*b);
};

using type_name_map = std::map<
    std::type_info const*,
    char const*,
    decltype(type_info_less)
>;

auto const readable_type_names = type_name_map(
    {
        {& typeid(int), "int"},
        {& typeid(float), "float"},
        {& typeid(std::string), "std::string"},
        // ...
    },
    type_info_less
);

template <typename T>
auto type_name() {
    return readable_type_names.find(& typeid(T))->second;
}

int main() {
    std::cout << type_name<std::string>() << "\n";
    // Prints ”std::string”.
}

请注意,我们需要存储指针,因为 type_info 不可复制或移动。

【讨论】:

  • 我会理解前两个问题,但我不明白什么是 type_info::before,我在谷歌上搜索过 type_info::before 但我无法得到他们所说的,所以你能解释一下这个。
  • 感谢您的回复。我不明白 type_info::before 如何返回 0 或 1。在某些网站中,他们说函数根据实现的排序顺序返回。但这是什么?
  • @Srilakshmikanthanp 它返回 bool,而不是 0 或 1。“排序顺序”是一种愚蠢而复杂的说法,它的功能类似于 C++ 中的 &lt; 运算符。换句话说,它可以用来对type_info 值进行排序(通过一些任意的排序标准...... 实际顺序 并不重要,重要的是它是一致的,因为std::map 使用这样的顺序查找元素)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
相关资源
最近更新 更多