我将 C++ 与 RTTI 一起使用。我有一个type_info班级。如果我只有 ,我如何判断另一个类是否是第一个类的子类type_info?
#include <typeinfo>
class Foo { public: virtual ~Foo() {} };
class Boo: public Foo { public: virtual ~Boo() {} };
class Bar { public: virtual ~Bar() {} };
template<class T>
bool instanceOf(const type_info& info) {
// ANSWER COMES HERE!!
}
int main(int argc, const char* argv[]) {
const type_info& fooInfo = typeid(Foo);
const type_info& barInfo = typeid(Bar);
bool booIsFoo = instanceOf<Boo>(fooInfo); // should be true
bool booIsBar = instanceOf<Boo>(barInfo); // should be false
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果你只有两个 typeinfo A 和 B。没有通用的方法来确定 A 是否是 B 的子类。
您可以:
以前的答案。它们要求您以某种方式实例化类型:
type_info不是合适的工具,dynamic_cast如果你绝对想在运行时检查,你应该这样做:
template<class Base, typename Derived>
bool instanceOf(const Derived& object) {
return !dynamic_cast<Base*>(object);
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用std::is_base_ofSteephen 提到的方法在编译时进行检查(需要 C++11)。
template <typename Base, typename Derived>
static constexpr bool instanceOf() {
return std::is_base_of<Base, Derived>()
}
Run Code Online (Sandbox Code Playgroud)
另一个解决方案:
template <typename Base, typename Derived>
bool instanceOf(const Derived& object) {
try {
throw object;
} catch (const Base&) {
return true;
} catch (...) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)