Explanation of std::function

前端 未结 6 1613
故里飘歌
故里飘歌 2020-12-31 09:58

What is the purpose of std::function? As far as I understand, std::function turns a function, functor, or lambda into a function object.

I

6条回答
  •  醉酒成梦
    2020-12-31 10:53

    One example of where std::function can be very useful is in implementing an "observer pattern". So, for example, say you want to implement a simple "expression evaluator" calculator GUI. To give a somewhat abstract idea of the kind of code you might write against a GUI library using the observer pattern:

    class ExprEvalForm : public GuiEditorGenerated::ExprEvalForm {
    public:
        ExprEvalForm() {
            calculateButton.onClicked([] {
                auto exprStr = exprInputBox.get();
                auto value = ExprEvaluator::evaluate(exprStr);
                evalOutputLabel.set(std::to_string(value));
            });
        }
    };
    

    Now, how would the GUI library's button class store the function that's passed to onClicked? Here, an onClicked method (even if it were templated) would still need to store somewhere into a member variable, which needs to be of a predetermined type. That's exactly where the type erasure of std::function can come into play. So, a skeleton of the button class implementation might look like:

    class PushButton : public Widget {
    public:
        using ButtonClickedCallback = std::function;
        void onClicked(ButtonClickedCallback cb) {
            m_buttonClickedCallback = std::move(cb);
        }
    
    protected:
        void mouseUpEvent(int x, int y) override {
            ...
            if (mouseWasInButtonArea(x, y))
                notifyClicked();
            ...
        }
    
    private:
        void notifyClicked() {
            if (m_buttonClickedCallback)
                m_buttonClickedCallback();
        }
        ButtonClickedCallback m_buttonClickedCallback;
    };
    

提交回复
热议问题