Thursday, October 2, 2008

c++: separate members from their classes

In my post c++: separate methods from their classes I described how to call class method by reference. The similar staff you can do with class members. Assume you have a collection of class instances and you want to print the values of some members from them. Again you can define two lists - list of class instances and list of pointers to class members. Later you can iterate through these list to touch members of the classes.

#include <iostream>
#include <list>

class A
{
    public:
        int m0; 
        int m1; 
};

template<typename T>
void
print(const T &a, 
    int T::*p)
{
    std::cout << a.*p << std::endl;
}

int main(int argc, char **argv)
{
    std::list<A> ls;
    std::list<int A::*> lsm;

    int A::*p0 = &A::m0;

    lsm.push_back(p0);
    lsm.push_back(&A::m1);

    A a0, a1; 
    a0.*p0 = 0;
    a0.m1 = 1;
    a1.m0 = 2;
    a1.m1 = 3;
    
    ls.push_back(a0);
    ls.push_back(a1);
    
    for (std::list<A>::iterator i = ls.begin();i!=ls.end();++i)
        for (std::list<int A::*>::iterator j = lsm.begin();j!=lsm.end();++j)
            print(*i, *j);

    return 0;
}
With this piece of code you will get
0
1
2
3
This method to access class members can be combined with class methods references to achieve more power.

No comments: