You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MSVC中type_info类型比较差异是否属于编译器Bug?

函数类型typeid比较的跨编译器差异问题

问题现象

我编写了如下代码,在不同编译器下得到了不一致的结果:

  • MSVC(x86,v19.32):typeid对两个函数的类型比较结果为false,但自定义类型判断模板are_types_same返回true
  • clang(x86-64,v14.0.0):typeid和are_types_same的判断结果均为true

请问这是否属于MSVC的编译器Bug?是否值得上报?

测试代码

#include <typeinfo>
#include <iostream>

void thing(char thing[2], int thing2) {

}

void thing2(char* thing, int thing2) {

}

template <typename T, typename U>
struct are_types_same {
    constexpr operator bool() const noexcept { return false; }
};

template <typename T>
struct are_types_same<T, T> {
    constexpr operator bool() const noexcept { return true; }
};

int main() {
    const std::type_info& info = typeid(thing);
    const std::type_info& info2 = typeid(thing2);

    std::cout << "typeid: " << (info == info2) << '\n';
    std::cout << "are_types_same: " << are_types_same<decltype(thing), decltype(thing2)>{} << '\n';
}

问题分析

  1. 函数类型的本质:根据C++标准,函数参数列表中的数组类型会被自动调整为指针类型,因此void(char[2], int)和void(char*, int)属于同一函数类型。decltype(thing)和decltype(thing2)会得到完全相同的类型,这也是自定义模板are_types_same返回true的原因。
  2. typeid的标准行为:C++标准明确规定,对于同一类型的不同表达式,typeid必须返回指向同一个std::type_info对象的引用,因此info == info2的结果应该为true。

结论

MSVC的行为不符合C++标准,属于编译器Bug。这种不一致会破坏代码的可移植性,值得上报给微软编译器团队。

内容的提问来源于stack exchange,提问作者Nik Tedig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:15:33