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

后端 未结 2 602
甜味超标
甜味超标 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: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 inline bool instanceof(const T) {
       return is_base_of::value;
    }
    
    int main() {
       Module1 module;
       if(instanceof(module)) {
          cout << "Module1" << endl;
       }
       if(instanceof(module)) {
          cout << "Module2" << endl;
       }
       if(instanceof(module)) {
          cout << "ModuleBase" << endl;
       }
    }
    

    2 Live sample

    class ModuleBase { public: virtual ~ModuleBase(){} };
    
    template inline bool instanceof(const ModuleBase * base) {
       return dynamic_cast(base);
    }
    
    int main() {
    
       Module1* module = new Module1();
    
       if(instanceof(module)) {
          cout << "Module1" << endl;
       }
       if(instanceof(module)) {
          cout << "Module2" << endl;
       }
       if(instanceof(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.

提交回复
热议问题