如何检查派生类的类型? (C ++ Instanceof) [英] How can I check the types of derived classes? (C++ Instanceof)

查看:215
本文介绍了如何检查派生类的类型? (C ++ Instanceof)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些基本的抽象类和三个派生和实现其方法的不同类.是否像C#中那样有一个类型"对象?换句话说,如何获得所有这些类的实例?

Let's say I have some base abstract class and three different classes that derive and implement its methods. Is there is a 'Type' object like as in C#? Or in other words, how do I get instances of all these classes?

#ModuleBase.cpp
class ModuleBase {

};

#Module1.cpp
class Module1 : public virtual ModuleBase {

};

#Module2.cpp
class Module2 : public virtual ModuleBase {

};

#Module3.cpp
class Module3 : public virtual ModuleBase {

};

推荐答案

您可以创建类似于instanceof的方法,这些方法可以使用模板和 1 )或仅 dynamic_cast 用于多态对象( 2 ).

You can create instanceof like methods that can detect the type of an object using templates and std::is_base_of (1) or dynamic_cast only for polymorphic objects (2).

1 实时示例

template<typename Base, typename T> inline bool instanceof(const T) {
   return is_base_of<Base, T>::value;
}

int main() {
   Module1 module;
   if(instanceof<Module1>(module)) {
      cout << "Module1" << endl;
   }
   if(instanceof<Module2>(module)) {
      cout << "Module2" << endl;
   }
   if(instanceof<ModuleBase>(module)) {
      cout << "ModuleBase" << endl;
   }
}

2 实时示例

class ModuleBase { public: virtual ~ModuleBase(){} };

template<typename T> inline bool instanceof(const ModuleBase * base) {
   return dynamic_cast<const T*>(base);
}

int main() {

   Module1* module = new Module1();

   if(instanceof<Module1>(module)) {
      cout << "Module1" << endl;
   }
   if(instanceof<Module2>(module)) {
      cout << "Module2" << endl;
   }
   if(instanceof<ModuleBase>(module)) {
      cout << "ModuleBase" << endl;
   }
}

对象的类型均为ModuleBaseModule1.我认为您可以通过这些实现您所需要的.

The object is both of type ModuleBase and Module1. I think with that you can achieve what you need with these.

这篇关于如何检查派生类的类型? (C ++ Instanceof)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆