How to hash and compare a pointer-to-member-function?

前端 未结 3 845
無奈伤痛
無奈伤痛 2020-11-27 08:23

How can i hash (std::tr1::hash or boost::hash) a c++ pointer-to-member-function?

Example:

I have several bool (Class::*functionPointer)() (not static) that

3条回答
  •  囚心锁ツ
    2020-11-27 08:39

    If your member function pointer is unique, which is true in most of cases for callback-based subscriptions, then you can use the tick with type_index, which uniqueness is guaranteed by uniqueness of type (i.e. Class::Method) in your program, and it is suitable to be stored in unordered_map, i.e.

    struct MyEvent {
    
        using fn_t = std::function;
        using map_t = std::unordered_map;
    
    
        template 
        void subscribe(Object& obj, Handler&& handler) {
            fn_t fn = [&, handler = std::move(handler)](MyEvent& event) {
                (obj.*handler)(event);
            }
            std::type_index index = typeid(Handler);
            subscribers.emplace(std::move(index), std::move(fn));
        }
    
        void fire() {
            for(auto& pair: subscribers) {
                auto& fn = pair.second;
                fn(*this);
            }
        }
    
        map_t subscribers;
    }
    

    And the subscription and fire event example:

    MyEvent event;
    MyObject obj = ...;
    event.subscribe(obj, &MyObject::on_event );
    ...
    event.fire();
    

    So, example above gives you class/method uniqueness, and if you need object/method uniqueness, then you should have an struct, which provides combined hash, assuming that there is std::hash and there is already std::hash for a member function pointer.

提交回复
热议问题