相当于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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短