C ++:使用typeinfo测试类继承 [英] C++: using typeinfo to test class inheritance
问题描述
我有一个指向多态类型的指针, p
。我也有一个 type_info
在同一层次中的某个类, ti
。
I have a pointer to a polymorphic type, p
. I also have a type_info
for a class somewhere in the same hierarchy, ti
.
如果我只是比较 typeid(* p)== ti
,那么我可以在运行时测试指针是否指向一个直接实例。
If I just compare the typeid(*p) == ti
, then I can test at runtime whether the pointer is pointing to a direct instance of that class.
是否有类似的方法使用C ++的RTTI来测试 * p
inherits
Is there a similar way to use C++'s RTTI to test whether *p
inherits from that class?
推荐答案
在标准C ++中没有办法做到这一点。如果您使用的实施包含 Itanium C ++ ABI 1 ,你可以这样做,例如:
There's no way to do this in standard C++ alone. If you're using an implementation that has the Itanium C++ ABI1 you can do this though, for example:
#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
。
Here this works because the type has a single, non-virtuallly inherited base. You can support more cases though with care and similar dynamic_casts
.
虽然这是可能的,你解决了错误的问题虽然 - 基于 std :: map
的解决方案是更便携,避免依赖于这样的实现细节。
Whilst this is possible under these certain circumstances I think you're solving the wrong problem though - a solution based around a std::map
is more portable and avoids relying on implementation details like this.
1 混淆地命名,它是一个惊人的大型编译器/体系结构列表,而不仅仅是Itanium
1 confusingly named, it's a surprisingly large compiler/architecture list, not just Itanium
这篇关于C ++:使用typeinfo测试类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!