类型id结果不匹配
typeid results not matching
我有一个功能:
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中编译,但不清楚结果意味着什么。这段代码在gcc
和clang
中都不能编译。
为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
相关文章:
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- 在使用累加时,C++中的运算符+不匹配
- C++ 与操作员不匹配<<
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 与'operator='不匹配(操作数类型'String'且"void")
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- C4018:类内有符号、无符号不匹配
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- RE2 不匹配非 ASCII 字符
- C++公式与指定值不匹配的结果
- 我的 AQTime 结果中的次数总和与我测量的响应时间不匹配
- 使用 Pycrc 和 PHP 代码的 CRC32 计算与预期结果不匹配
- 在提升匹配结果中查找不匹配
- Java 和 C++ 加密结果不匹配
- 类型id结果不匹配
- CLOCKS_PER_SEC与std::clock()的结果不匹配
- OpenCV idft() 和 MATLAB ifft2 的结果不匹配
- Qt:QProcess 结果与提示时的结果不匹配