类型id结果不匹配

typeid results not matching

本文关键字:不匹配 结果 id 类型      更新时间:2023-10-16

我有一个功能:

 void func(unsigned int event) {
       printf("%u %urn", typeid(event), typeid(unsigned int&));
    // prints 5338164 0
       printf("%u %urn", typeid(event), typeid(unsigned int));
    // prints 21525556 0
}

假设这个问题与rtfm相关,但我重读了typeid() man page几次,却找不到答案。这段代码有什么问题?为什么%u不相等?也为什么它改变第一个%u时,我改变了代码中的第二个参数。谢谢。

Try

printf("%s %sn", typeid(event).name(), typeid(unsigned int).name());

正如前面的回复所说,typeid()的结果是不透明的,不能像int一样打印。这段代码无法编译的原因是C语言的错误类型。

所以typeid返回std::type_info而不是unsigned int。这似乎可以在Visual Studio中编译,但不清楚结果意味着什么。这段代码在gccclang中都不能编译。

printf使用错误的格式说明符是未定义的行为,因此该行为确实不可预测。Visual Studio不必为此产生警告,但这样做将有助于防止此类问题的发生。由于std::type_info不是一个平凡的类,它是在可变函数中使用的实现定义行为,因此clang产生以下警告:

error: cannot pass non-trivial object of type 'const std::type_info' to variadic function; expected type from format string was 'unsigned int' [-Wnon-pod-varargs]
 printf("%u %urn", typeid(event), typeid(unsigned int));
         ~~  

使用std::type_info::name返回一个const char将得到您期望的结果:

 printf("%s %sn", typeid(event).name(), typeid(unsigned int&).name());

和Visual Studio的结果:

unsigned int unsigned int
unsigned int unsigned int