samedi 10 octobre 2020

Is there any way to convert a superclass pointer to subclass pointer by subclass name in c++ string?

Recently, I'm working on something like reflection in c++ using by my plugin system. Right now, I wonder if I can convert a super-class pointer into sub-class pointer given the string name of sub-class:

class SuperClass
{
public:
  SuperClass(const string &name):class_name(name){}
  // a convert function like
  // return value should variant like SubClassA * or SubClassB *
  // SubClassA * ConvertByName();

private:
  string class_name;
};

class SubClassA: public SuperClass
{
public:
  SubClassA():SuperClass("SubClassA")
};

class SubClassB: public SuperClass
{
public:
  SubClassB():SuperClass("SubClassB")
}

when using:

// some place create instance
SuperClass *one = new SubClassA;
SuperClass *two = new SubClassB;


// other place using
auto a = one->ConvertByName();  // a is of type SubClassA
auto b = two->ConvertByName();  // b is of type SubClassB

Can it be realized? Or is there any better way in c++?

[Update 1]

There my be some other sub-classes, such as, SubClassC, SubClassD, ... So basically, we don't know what and how many sub-classes are derived from this SuperClass. What we know about sub-class is only its class name in string format.

[Update 2]

My motivation

I need this for plugin system. I want to create a plugin anytime, but don't want hack into my plugin core system codes. That is plugin codes are isolated from projects. A plugin system will never know what and how many plugins are added into system until runtime

Aucun commentaire:

Enregistrer un commentaire