std::type_index可安全高效作异构容器键,但须开启rtti、统一类型表示、避免cv修饰符错配;typeid(t).name()跨编译器不一致且无类型语义,而std::type_index提供语义等价比较。

直接用 std::type_index 做异构容器的键是安全且高效的,但必须统一类型表示、开启 RTTI、避免修饰符错配——否则查不到、崩溃或行为未定义。
为什么不能用 typeid(T).name() 当键
字符串名跨编译器不一致(GCC 返回 "i",Clang 可能是 "int"),且无类型语义;std::type_index 是语义等价比较,std::type_index{typeid(int)} 和 std::type_index{typeid(const int)} 天然不等,而字符串比较完全无法反映这点。常见错误现象:注册时用 typeid(MyClass),查询时传 typeid(const MyClass&),结果 find() 返回 end()。
- 永远不要对
typeid结果取地址存指针——typeid返回的是临时std::type_info,生命周期仅限表达式内 - 模板函数中获取
std::type_index必须作用于具体对象,如std::type_index{typeid(T{})},而非裸typeid(T)(后者在某些上下文可能未定义) -
std::type_index的name()仅用于调试,不可用于逻辑判断
std::unordered_map<:type_index t></:type_index> 编译失败?检查 <typeindex></typeindex> 和哈希特化
标准库从 C++11 起已为 std::type_index 特化 std::hash,但前提是包含头文件 <typeindex></typeindex>(不是 <typeinfo></typeinfo>)。若仍报错“no match for call to ‘std::hash<:type_index>’”,说明编译器未启用该特化(极少见),需手动提供:
struct type_index_hash {
size_t operator()(const std::type_index& ti) const noexcept {
return ti.hash_code();
}
};
std::unordered_map<:type_index std::function>()>, type_index_hash> factory;</:type_index>
-
hash_code()值只保证单次运行内稳定,不能用于持久化或网络传输 - 不要把
hash_code()当作类型唯一 ID——它只是哈希桶索引,不同类型可能碰撞 - 若用
std::map,无需额外哈希器,std::type_index自带operator(基于内部 <code>std::type_info::before())
多态对象识别:传 *ptr,别传 ptr
typeid(ptr) 返回的是指针类型(如 Derived*),而 typeid(*ptr) 才触发 RTTI 多态识别,返回实际动态类型(如 Derived)。在事件总线或插件系统中,若按消息类型路由,必须用解引用:
// 正确:按消息对象的实际类型分发
handlers.find(std::type_index{typeid(*msg_ptr)});
// 错误:只会匹配到 "MyMessage*" 类型,不是你想要的
handlers.find(std::type_index{typeid(msg_ptr)});
- 对空指针调用
typeid(*ptr)会抛出std::bad_typeid,务必先判空 -
std::type_index{typeid(obj)}和std::type_index{typeid(*ptr)}在多态场景下语义等价,但前者更安全(无空指针风险) - 前置声明类不能用于
typeid——类型必须有完整定义,否则编译失败
最易被忽略的点:RTTI 不是默认可选的“功能开关”,而是编译器底层机制。GCC/Clang 默认开启,但嵌入式项目常加 -fno-rtti;一旦关闭,typeid 行为未定义,std::type_index 构造即失效。上线前务必确认构建配置里没关 RTTI。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











