假设我们有一个基类和一系列派生类。有没有任何方法或机制可以通过编程知道所有派生类的名称?
也许反射是一个好主意,但在C++中不可用。我想可能会有某种模板可以在编译期间完成这项工作。
也许反射是一个好主意,但在C++中不可用。我想可能会有某种模板可以在编译期间完成这项工作。
class Base{
public:
virtual void print(){
// This function should print all the names of derived class.
}
virtual Base* getInstance(string class_name){
// This function should return an instance related to the class name.
}
};
class Derived_1 : public Base{ // Suppose we have 100 Derived_X classes,
// so we don't want to add its name to a list manually.
};
int main(){
Base base;
base.print(); // This should print the name of all the derived class.
base.getInstance("Derived_1"); // This should return an instance of Derived_1
return 0;
}