平台之间的不同类型

Diffrent typeid between platforms

我不明白为什么这个程序使用相同的编译器在 Linux 和 Windows 之间产生不同的输出。在 Windows 中输出 float,在 Linux 中输出 f.

#include <typeinfo>
#include <iostream>

int main() {
        std::cout << typeid(float).name() << std::endl;
        return 0;
}

来自[expr.typeid]/1

The result of a typeid expression is an lvalue of static type const std​::​type_­info and dynamic type const std​::​type_­info or const name where name is an implementation-defined class publicly derived from std​::​type_­info which preserves the behavior described in [type.info]. [...]

名字是implementation-defined。

[type.info]/1 特别提到[强调 我的]:

The class type_­info describes type information generated by the implementation. Objects of this class effectively store a pointer to a name for the type, and an encoded value suitable for comparing two types for equality or collating order. The names, encoding rule, and collating sequence for types are all unspecified and may differ between programs.

指向的类型的名称未指定,并且可能不仅在实现之间有所不同,甚至在程序之间(来自相同的实现)也可能不同。

typeid operator returns the name from the std::type_info,描述为

The class type_info holds implementation-specific information about a type, including the name of the type and means to compare two types for equality or collating order. This is the class returned by the typeid operator.

因此,implementation-specific 他们如何选择命名类型。这在 std::type_info::name

中再次得到加强

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.

有治愈的方法。 boost has demangling 功能。

#include <iostream>
#include <boost/core/demangle.hpp>
#include <typeinfo>


int main()
{
    auto name = typeid(float).name();
    std::cout << name << std::endl;
    std::cout << boost::core::demangle(name) << std::endl;
    
    return 0;
}

简单demo

更复杂demo