Delegate in C++11

后端 未结 5 874
悲&欢浪女
悲&欢浪女 2021-02-14 00:09

Does C++11 provide delegates?

If not, what is the best (most efficient) way to do something similar in C++? Boost.Signals? FastDelegate? Something else?

5条回答
  •  情话喂你
    2021-02-14 00:37

    You can get delegate-like semantics using bind to bind a member function to a class instance:

    #include 
    
    struct C 
    {
        void Foo(int) { }
    };
    
    void Bar(std::function func) 
    { 
        func(42); // calls obj.Foo(42)
    }
    
    int main() 
    {
        using namespace std::placeholders;
    
        C obj;
        Bar(std::bind(&C::Foo, obj, _1));
    }
    

    In this example, Bar() takes anything that has a single int parameter and that returns void.

    In main(), we bind a pointer to the member function C::Foo to the instance of C named obj. This gives us an object that can be called with a single int parameter and which returns void.

    We call Bar() with this object and Bar() makes the call obj.Foo(42).

提交回复
热议问题