如何检查派生类型 类? (C++ 实例)

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

假设我有一些基础抽象 class 和三个不同的 class 派生和实现其方法。是否有像 C# 中那样的 'Type' 对象?或者换句话说,我如何获得所有这些 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 类方法,使用模板和 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;
   }
}

该对象是 ModuleBaseModule1 类型。我认为有了这些你就可以实现你所需要的。

除了其他答案之外,您还可以生成 一些 C++ 代码来执行您想要的操作。例如,考虑使用 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 在 Linux.

上(动态地,在运行时)做到这一点

Qt has a meta-object protocol doing exactly this. You might get inspiration from its moc(开源)生成 C++ 代码。

另请查看正在进行的(但 - 在 2020 年 2 月 - 胚胎)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,关于通过编译生成的和临时的 C++ 代码生成的共享对象。