How can I check the types of derived classes in C++?

拜拜、爱过 提交于 2020-03-03 08:25:40

问题


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 {

};

回答1:


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 Live sample

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 Live sample

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;
   }
}

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




回答2:


In addition to other answers, you might generate some C++ code doing what you want. Consider for example using GPP from your build automation tool (e.g. Makefile) or write a simple AWK, Guile, or Python script doing what you want (or some ad-hoc C++ generator above ANTLR, inspired by SWIG), and generating some C++ code per your needs. My obsolete GCC MELT did that (dynamically, at runtime) on Linux.

Qt has a meta-object protocol doing exactly this. You might get inspiration from its moc (which is open source) generating C++ code.

Look also into the ongoing (but -in February 2020- embryonic) RefPerSys project. We want to use these ideas, and we are starting to implement them. Observe that on Linux dlopen could be called thousands of times in practice, on shared objects produced by compilation of generated and temporary C++ code.



来源:https://stackoverflow.com/questions/60066535/how-can-i-check-the-types-of-derived-classes-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!