Tuesday, January 22, 2008

c++: separate methods from their classes

If you have a list of objects and a list of functions(list of methods of those objects you want to call) sometimes you use a loop where you call all methods of object line by line. That's acceptable method but I want to propose you another one: to have a list of objects and a list of pointers to their methods. Defined class hierarchy.

class One
{
    public:
    virtual void draw0() = 0;
    virtual void draw1() = 0;
};

class Two: public One
{
    public:
    virtual void draw0()
    {
        std::cout << __func__ << std::endl;
    }
    virtual void draw1()
    {
        std::cout << __func__ << std::endl;
    }
};
Define function that will call objects' method by their address.
template<typename T>
void
draw(T *b, void (T::*f)())
{
    (b->*f)();
}
Define two lists: objects and their methods.
    std::list<One *> ls;
    std::list<void (One::*)()> lsm;
Push methods you want to call to the list of methods.
    lsm.push_back(&One::draw0);
    lsm.push_back(&One::draw1);
And push objects to the list of objects.
    Two T0, T1;
    ls.push_back(&T0);
    ls.push_back(&T1);
Now you can just iterate on list of objects and on list of their methods.
    for (std::list<One *>::iterator i(ls.begin()), j(ls.end());i!=j;++i)
        for (std::list<void (One::*)()>::iterator o(lsm.begin()), p(lsm.end());o!=p;++o)
            draw(*i, *o);
Using this example you should get
draw0
draw1
draw0
draw1
at the output.

No comments: