相当于instanceof的C ++
C++没有直接方法来检查一个对象是否是某些类类型的实例。在Java中,我们可以获得这种便利。
在C++11中,我们可以找到一个名为is_base_of<Base,T>的项目。这将检查给定的类是否为给定对象的基础。在这里,我们将像javainstanceof一样更改其样式。让我们看看代码。
范例程式码
#include <iostream> using namespace std; template<typename Base, typename T> inline bool instanceof(const T*) { return is_base_of<Base, T>::value; } class Parent{ }; class Child : Parent { }; class AnotherClass{}; int main() { Child *c; if(instanceof<Child>(c)) { cout << "c is instance of Child class" << endl; } else { cout << "c is not instance of Child class" << endl; } if(instanceof<Parent>(c)) { cout << "c is instance of Parent class" << endl; } else { cout << "c is not instance of Parent class" << endl; } if(instanceof<AnotherClass>(c)) { cout << "c is instance of AnotherClass class" << endl; } else { cout << "c is not instance of AnotherClass class" << endl; } }
输出结果
c is instance of Child class c is instance of Parent class c is not instance of AnotherClass class