1

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.

  • Read ["How can I add reflection to a C++ application?"][1] and see if it solves your problem. [1]: http://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application – Tom Solacroup Aug 03 '15 at 10:44
  • @Tom: Good find, that's effectively a duplicate. – DevSolar Aug 03 '15 at 10:46

2 Answers2

3

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.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
David Haim
  • 25,446
  • 3
  • 44
  • 78
  • I had this exact nagging doubt when I wrote "as far as I know". C++ just keeps surprising you with things it can do, or will be able to do. ;-) – DevSolar Aug 03 '15 at 10:49
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++.

DevSolar
  • 67,862
  • 21
  • 134
  • 209