为什么在枚举名称中的字符数量之前先枚举打字机

Why enumeration typenames are preceded with the number of characters in the enumeration name?

本文关键字:枚举 打字机 为什么 字符      更新时间:2023-10-16

考虑以下代码:

#include <iostream>
#include <typeinfo>
enum class Colors
{
    Red,
    Blue,
    Green
};
int main ()
{
    std::cout << typeid(Colors::Red).name();
    return 0;
}

上述程序的输出为6Colors。即使枚举"未划分"(没有class关键字的枚举),也是如此。Animals定义了另一个枚举时,其类型名称将变为7Animals。尽管这在将来可能几乎没有考虑,但我很想知道编译器为什么这样做。

您正在看到一个杂乱无章的名称 - 该名称旨在编码名称范围和键入信息以及名称。

Boost具有方便的跨平台方法,可以删除这些名称,您可能会发现有趣的玩法:

#include <iostream>
#include <typeinfo>
#include <boost/core/demangle.hpp>
enum class Colors
{
    Red,
    Blue,
    Green
};
int main ()
{
    std::cout << boost::core::demangle(typeid(Colors::Red).name());
    return 0;
}