std::function and std::bind: what are they, and when should they be used?

后端 未结 4 454
眼角桃花
眼角桃花 2020-11-29 14:39

I know what functors are and when to use them with std algorithms, but I haven\'t understood what Stroustrup says about them in the C++11 FAQ.

Can anyon

4条回答
  •  佛祖请我去吃肉
    2020-11-29 15:09

    One of the main use of std::function and std::bind is as more generelized function pointers. You can use it to implement callback mechanism. One of the popular scenario is that you have some function that is going to take long time to execute but you don't want to wait for it to return then you can run that function on separate thread and give it a function pointer that it will callback after it completes.

    Here's a sample code for how to use this:

    class MyClass {
    private:
        //just shorthand to avoid long typing
        typedef std::function TCallback;
    
        //this function takes long time
        void longRunningFunction(TCallback callback)
        {
            //do some long running task
            //...
            //callback to return result
            callback(result);
        }
    
        //this function gets called by longRunningFunction after its done
        void afterCompleteCallback(float result)
        {
            std::cout << result;
        }
    
    public:
        int longRunningFunctionAsync()
        {
            //create callback - this equivalent of safe function pointer
            auto callback = std::bind(&MyClass::afterCompleteCallback, 
                this, std::placeholders::_1);
    
            //normally you want to start below function on seprate thread, 
            //but for illustration we will just do simple call
            longRunningFunction(callback);
        }
    };
    

提交回复
热议问题