如何静态断言不同第三方库中两个字段的类型一致?
C++静态断言类型相等的正确写法
你给出的原始代码结构如下:
// library 1: struct A { struct B { std::map<std::string, int> LookupTable; }; B b; }; // library 2: struct C { std::map<std::string, int> LookupTable; };
要实现你想要的静态类型断言,不能用非标准的typeof或运行时的typeid,标准C中可以用<type_traits>头文件里的std::is_same(C11起)或std::is_same_v(C++17起)来完成编译期类型检查。以下是对应三个场景的正确代码:
1. 断言A::B::LookupTable与C::LookupTable类型相同
#include <type_traits> #include <map> #include <string> static_assert(std::is_same_v<decltype(A::B::LookupTable), decltype(C::LookupTable)>); // C++11/14兼容版本:static_assert(std::is_same<decltype(A::B::LookupTable), decltype(C::LookupTable)>::value);
2. 断言A::B::LookupTable与std::map<std::string, int>类型相同
static_assert(std::is_same_v<decltype(A::B::LookupTable), std::map<std::string, int>>); // C++11/14兼容版本:static_assert(std::is_same<decltype(A::B::LookupTable), std::map<std::string, int>>::value);
3. 断言对象成员的类型(注意你原代码中的a.x应为a.b.LookupTable)
A a; static_assert(std::is_same_v<decltype(a.b.LookupTable), std::map<std::string, int>>); // C++11/14兼容版本:static_assert(std::is_same<decltype(a.b.LookupTable), std::map<std::string, int>>::value);
关键说明:
decltype是标准C++运算符,用于编译期获取表达式的类型,替代非标准的typeof。std::is_same是类型特性模板,用于判断两个类型是否完全相同;std::is_same_v是C++17引入的便捷变量模板,等价于std::is_same<T,U>::value。typeid返回运行时类型信息,无法用于编译期的static_assert,因为static_assert要求表达式为编译期常量。
内容的提问来源于stack exchange,提问作者Zaaier
相关产品推荐
相关产品推荐

