How to get a list of a class's member variable

2019-08-11 16:41发布

问题:

This question already has an answer here:

  • How can I add reflection to a C++ application? 32 answers

Is there a way that I could obtain a list or maybe iterate through a list of each member variable of a class -regardless of it's type.

My intention is to add them all to a template std::map.

class Person
{
    int Age;
    char *Name;
    template<typename Container> std::map<char *, Container> List;
    void MakeList()
    {
       for(auto i : Person.memberVariables)
       {
           List.emplace(i);
       }
    }
};

Could I do something like the above to add each variable of my class to the list, regardless of how incorrect the other code is. The adding to the list is what I'm interested in.

Thanks in advance.

回答1:

No, you can't do it in C++. this is called reflection which is currently not supported in C++.

The ISO C++ comitee talks about compile time reflection that is proposed for C++17 that will let you to iterate over class members on compile time. but it will take much time until this feature will be standarized and be implemented on the common compilers

as a side note, I don't see why one would want to iterate over member variables other then maybe implementing serialization method , which in this case I would require the class to implement serialize method and enforce it with SFINAE.



回答2:

If there is, I would be very surprised.

This is called reflection, and as far as I know this isn't supported by C++.