c++ - delegate实现c++,如何找到具体的类成员函数

标签 c++ c++11 std-function

我正在研究如何使用 c++11 实现简单的委托(delegate)。问题是断开连接方法,我想将特定对象的特定功能从 map 中删除。通过此实现,我删除了连接到特定对象实例的所有函数。我希望能够做类似的事情:

delegate.disconnect (myobj, &MyObj::method)

而不是

delegate.disconnect (myobj)

它会删除 myobj 的所有相关函数。

template <typename ... Params >
class Delegate {

private:    
    typedef std::function < void (Params...)> FunctionType;
    std::map < void*, std::vector < FunctionType >> m_functions;

public:
    template <typename Class>
    void connect(Class& obj, void (Class::*func) (Params...) ) 
    {
        std::function < void (Class, Params...) >  f = func;
        FunctionType fun = [&obj, f](Params... params) { f(obj, params...); };
        m_functions[&obj].push_back(fun);
    }

    template <typename Class>
    void disconnect(Class& obj) {
        m_functions.erase(&obj);
    }

    template <typename ... Args>
    void operator() (Args...args)
    {       
        for (auto& pair : m_functions) {
            for (auto& func : pair.second) {
                func(args...);
            }
        }
    }
};

最佳答案

我找到了一种散列成员函数的方法,这正是我所需要的,所以我在这里回答我自己的问题:

template <typename Class>
size_t getHash(void (Class::*func) (Params...)) {
    const char *ptrptr = static_cast<const char*>(static_cast<const void*>(&func));
    int size = sizeof (func);
    std::string str_rep(ptrptr, size);
    std::hash<std::string> strHasher;
    return strHasher(str_rep);
}

现在使用很简单:

delegate.disconnect(&MyClass::MyFunc);

引用: How to hash and compare a pointer-to-member-function?

关于c++ - delegate实现c++,如何找到具体的类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227310/

相关文章:

c++ - 我怎样才能与其他人无误地分享我的 SFML 游戏?

c++ - 仅更改 const-ness 的指针转换可以调用未定义的行为吗?

c++ - std::call_once 是否可重入且线程安全?

c++ - UTF-8 字符串的按位异或运算给出非 UTF-8 输出

c++ - 类中重载成员函数的 std::function 初始化

c# - 如何替换c#中的保留关键字(类似于c++宏)?

c++ - 更改无序 multimap 中的键

C++:使用 std::function 在多重集中插入​​元组,并保持顺序

c++ - 如何将函数的指针从std::function传递给Linux克隆?

c++ - 如果我定义了一个构造函数,为什么我必须使用指针?