1

我正在尝试实现一个回调管理器,它可以注册和执行来自不同类的回调,每个类都来自不同的 DLL。

这些类中的每一个都派生自一个公共基类。我知道单个类如何使用如下模板类来注册和调用自己的函数,但是如何将其应用于共享同一个回调管理器的多个类?

任何帮助将不胜感激。

file: callbacktemplate.h
------------------------
#include <functional>
#include <string>
template <class cInstance>
class cCallBackManager
{
private:
    typedef void (cInstance::*tFunction)();
    typedef std::map<std::string, tFunction> funcMap;
     funcMap i_funcMap;
public:
    void SetFunPointer(std::string funcName, tFunction function)
    {
        i_funcMap.insert(std::pair<std::string, tFunction>(funcName, function));            
    }

    void GetFunPointer(cInstance& obj) //how to call this without knowing the type?
    {
        for (funcMap::iterator it = i_funcMap.begin();it!=i_funcMap.end(); ++it)
        {
            (obj.*(it->second))(); 
        }
    }
};


file:example.h
---------------
#include "callbacktemplate.h"
class A: public base
{
private:
    cCallBackManager<A> callback;
public:
     A()
     {
         callback.SetFunPointer<A>("eventA", &A::testcallback);
         callback.GetFunPointer(&this);   //how to generalize this so this can be called from the callback manager with the class object?
     };
     ~A(){};
     void testCallback();
};

class B: public base
{
private:
    cCallBackManager<B> callback;
public:
     B()
     {
         callback.SetFunPointer<B>("eventB", &B::testcallback);
     };
     ~B(){};
     void testCallback();
};

file: main.cpp
------------------
#include "derived.h"

int main()
{
 A a;
 B b;
 //create a callback manager to execute the callback?
 callbackmgr.execute() //execute all the callback

 return 0;
}

如果不使用模板化回调管理器,我该如何实现 SetFunPointer(EVENT_NAME, (Base Class)A::testCallback)?

4

2 回答 2

1

多谢你们。我已经设法用你的“指针”想出了一些东西。:)

文件:cCallBackInterface.h

template<class cClass>
class cCallBackInterface
{
public:
cCallBackInterface(){};
~cCallBackInterface(){};

typedef void (cClass::*Function)();

cCallBackInterface(cClass* obj, Function _Function)
{
    cInstance = obj;
    m_Function = _Function;
}

void execute()
{
     (cInstance->*m_Function)();
}

private:
cClass* cInstance;
Function m_Function;
};

文件:base.h

class BaseModel;
typedef cCallBackInterface<BaseModel> CallBackInterface;
typedef void(BaseModel::*basefn)();

class BaseModel 
{
public:
BaseModel(){};
~BaseModel(){};

}
};


class derived : public BaseModel
{
public:
derived(){};
~derived(){};

void dosomething()
{
    cout << "derived class is doing something." << endl;
}


};

文件:main.cpp

int main()
{  
derived a;

std::vector<CallBackInterface> callback;

callback.push_back(CallBackInterface(&a, (basefn)(&derived::Adosomething)));

for(int i = 0; i < callback.size(); i++)
    callback[i].execute();

return 0;
}
于 2012-07-08T03:44:27.580 回答
0

您可以查看有关使用成员函数指针的问题。

它归结为您需要实例以及 mem-func 指针,您不能在任何地方使用通用的。

于 2012-07-07T11:15:03.537 回答