How can I check the types of derived classes? (C++ Instanceof)

后端 未结 2 600
甜味超标
甜味超标 2021-01-23 17:38

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

相关标签:
2条回答
  • 2021-01-23 18:26

    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.

    0 讨论(0)
  • 2021-01-23 18:31

    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.

    0 讨论(0)
提交回复
热议问题