I am working on a class that holds a vector of class member functions. While normal function pointers a quite easy to implement I have discovered that using pointers to member functions take a bit more thought.
My first attempt:
This works quite well. The only problem is that in order to access member variables I have to pass this to the function and cast it to a MyClass1 pointer before each call to a member variable.Code:typedef void *pData; typedef void(*pFunction)(pData); class MyClass1 { public: MyClass1() { m_a = 5; m_b = 10; } ~MyClass1() { } void Go(); static void f1(pData d) { std::cout<<"Member Function 1. a = " <<static_cast<MyClass1*>(d)->m_a <<"\n"; } static void f2(pData d) { std::cout<<"Member Function 2. b = " <<static_cast<MyClass1*>(d)->m_b <<"\n"; } private: std::vector<pFunction> m_VecFunc; int m_a, m_b; }; void MyClass1::Go() { m_VecFunc.push_back(&f1); m_VecFunc.push_back(&f2) ; std::vector<pFunction>::iterator iter; for (iter = m_VecFunc.begin(); iter != m_VecFunc.end(); ++iter) { (*iter)(this); } return; }
I'm not sure I like this. While it works it seems like more work than it should be, having to remember to cast each member variable before I use it.
So then I came up with my second approach.
This also works quite well. I no longer have to cast each member variable before I can use it. The only problem now is that for each member function I want to take the address of, I have to have a second function just to call it. And I still have to pass this to the calling function.Code:class MyClass2 { public: MyClass2() { m_a = 5; m_b = 10; } ~MyClass2() { } void f1() { std::cout<<"Member Function 1. a = " <<m_a <<"\n"; } void f2() { std::cout<<"Member Function 2. b = " <<m_b <<"\n"; } void Go(); void DoCallBack(pFunction f, pData x) { f(x); } // calls f(x) private: static void call_f1(pData d) { static_cast<MyClass2*>(d)->f1(); } static void call_f2(pData d) { static_cast<MyClass2*>(d)->f2(); } int m_a, m_b; std::vector<pFunction> m_VecFunc; }; void MyClass2::Go() { m_VecFunc.push_back(call_f1); m_VecFunc.push_back(call_f2); std::vector<pFunction>::iterator iter; for (iter = m_VecFunc.begin(); iter != m_VecFunc.end(); ++iter) { (*iter)(this); } return; }
I'm not sure I care for this either.
Is there a way of doing this so that I can directly use member variables without having to do any type casting?



LinkBack URL
About LinkBacks



