Search code examples
c++class-members

Accessing class members in c++


I got back coding in C++ after a long while and was wondering if there is a way to access data member of a class quickly for manipulation.

Assume a case where you have like 10 data members in a class which overloads a bunch of operators (thought of this while overloading operator=). Now you would want to add/subtract a few data members to the class. Is there a generic way to accomplish this without having to go to individual functions and change them? I'm thinking of a possibility of running through all the members of a class in a kind of loop construct.


Solution

  • As there is no built-in reflection in C++ (yet), you have to list all your members somewhere. One way to save you from doing this over and over again is to define a for_each_member method which passes every member to some functor:

    template <class F>
    void for_each_member(F f);
    

    Now you can easily apply arbitrary operations to all your members, and you only have to maintain one listing of members per class.

    Running example: http://coliru.stacked-crooked.com/a/c813fc73c5519ee0

    If you want to perform different actions for different subsets of member, you have to find a way to separate these apart. You could do this by type (as shown in the example) or you could additionally pass some kind of identifier to your functor in for_each_member.

    Here I use a macro to pass both the member and its name to the functor: http://coliru.stacked-crooked.com/a/5a59c027e25c33fb