C++ map of “events” and member function pointers

后端 未结 2 561
礼貌的吻别
礼貌的吻别 2021-01-26 07:03

I\'ve managed to write a template class to work like a callback, learned from the accepted answer of this question How to define a general member function pointer.

I wis

相关标签:
2条回答
  • 2021-01-26 07:15

    There's no need for inheritance here. Just use std::function to store the member function pointers and std::bind to bind together the member function pointer and the object instance.

    #include <functional>
    #include <map>
    #include <string>
    #include <iostream>
    
    struct Apple {
        void Red () {
            std::cout << "aa\n";
        }
    };
    
    struct Orange {
        void Blue () {
            std::cout << "bb\n";
        }
    };
    
    int main()
    {
        std::map<std::string, std::function<void()>> m;
        Apple a;
        Orange o;
    
        m["apple"] = std::bind(&Apple::Red, a);
        m["orange"] = std::bind(&Orange::Blue, o);
    
        m["apple"]();
        m["orange"]();
    }
    

    Output:

    aa
    bb
    
    0 讨论(0)
  • 2021-01-26 07:22

    Madness lies, this way: Don't bind callbacks to specific classes. Instead, use a std::function<Signature> object and create suitable function objects: when you need to operate on different classes, you also need to operate on objects of different types. Using a std::function<...> should do the trick, e.g.:

    std::map<std::string, std::function<void()>> operations;
    operations["talk"] = std::bind(&ChildA::Talk, ChildA());
    operations["walk"] = std::bind(&ChildB::Walk, ChildB());
    operations["talk"]();
    
    0 讨论(0)
提交回复
热议问题