Using generic std::function objects with member functions in one class

前端 未结 6 2135
遥遥无期
遥遥无期 2020-11-22 09:41

For one class I want to store some function pointers to member functions of the same class in one map storing std::function objects. But I fail rig

6条回答
  •  灰色年华
    2020-11-22 10:26

    If you need to store a member function without the class instance, you can do something like this:

    class MyClass
    {
    public:
        void MemberFunc(int value)
        {
          //do something
        }
    };
    
    // Store member function binding
    auto callable = std::mem_fn(&MyClass::MemberFunc);
    
    // Call with late supplied 'this'
    MyClass myInst;
    callable(&myInst, 123);
    

    What would the storage type look like without auto? Something like this:

    std::_Mem_fn_wrap callable
    

    You can also pass this function storage to a standard function binding

    std::function binding = std::bind(callable, &testA, std::placeholders::_1);
    binding(123); // Call
    

    Past and future notes: An older interface std::mem_func existed, but has since been deprecated. A proposal exists, post C++17, to make pointer to member functions callable. This would be most welcome.

提交回复
热议问题