我有一个指向多态类型的指针,p
。我还有一个 type_info
用于同一层次结构中某处的类,ti
。
如果我只是比较 typeid(*p) == ti
,那么我可以在运行时测试指针是否指向该类的直接实例。
是否有类似的方法使用 C++ 的 RTTI 来测试 *p
inherits 从那个类?
最佳答案
仅在标准 C++ 中无法做到这一点。如果您使用的实现具有 Itanium C++ ABI 1 你可以这样做,例如:
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
#include <memory>
class base {
protected:
base() {
}
public:
static bool check(const std::type_info& p) {
// Find the real type_info for single inheritance non virtual
const __cxxabiv1::__si_class_type_info* test = dynamic_cast<const __cxxabiv1::__si_class_type_info*>(&p);
return test ? typeid(base) == *test->__base_type : false;
}
virtual ~base() {}
};
class der : public base {
};
class foo {};
int main() {
der d;
foo f;
std::cout << base::check(typeid(d)) << "\n";
std::cout << base::check(typeid(f)) << "\n";
}
之所以可行,是因为该类型有一个单一的、非虚拟继承的基础。你可以支持更多的案例,尽管小心和类似的 dynamic_casts
。
虽然在这些特定情况下这是可能的,但我认为您正在解决错误的问题 - 基于 std::map
的解决方案更便携,并且避免依赖像这样的实现细节。
1 令人困惑的命名,它是一个非常大的编译器/架构列表,而不仅仅是 Itanium
关于C++:使用类型信息测试类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491076/