dimanche 23 octobre 2016

How to enumerate a vector without knowing its element's type in reflection programming with C++11?

I'm trying to add dynamic reflection in C++ implementation with C++11. Let's say, I have a base class named Object:

class Object {
public:
    Object() = default;
    ~Object() = default;
};

And two classes inherited from Object:

class Person : public Object {
public:
    std::string name;
    int age;
}

class Group : public Object {
public:
    std::string groupName;
    std::vector<Person> persons;
}

I've implemented RefectManager to record all the classes' meta information, and I create an object with a class name, for example:

Object *obj = RefectManager::CreateObject("Group");
MetaInfo *groupMeta = obj->GetMetaInfo();

where, "groupMeta" holds the meta information of class Group, it knows that:

class Group has a field list with two fields inclued:
* one field named "groupName", and its type's name is "std::string"
* one field named "persons", and its type's name is "std::vector" and the name of the element's type in the vector is "Person"

I can get the Person's meta information through its name:

MetaInfo *personMeta = RefectManager::GetMetaInfo("Person");

But, is there a way to enumerate the field of "persons" in class Group with reflected meta informations dynamically, such as:

for (field in groupMeta's field list) {
    if (field type's name is "std::string") {
        get field's content as string
    } else if (field type's name is "std::vector") {
        // only the element type's name is known as "Person"

        // **how to enumerate the field with vector type?**

        // If we know the element's type through element type's name, 
        // we can do it as following:
        // std::vector<GetType<"Person">::type> *p = (std::vector<GetType<"Person">::type> *)field;
        // std::vector<GetType<"Person">::type>::iterator it = p->begin();
        // for (; it != p->end(); ++it) {
        //     //now we can access the element in field
        // }
    }
}





Aucun commentaire:

Enregistrer un commentaire