Explanation of std::function

前端 未结 6 1571
故里飘歌
故里飘歌 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:56

    In most uses that I've seen, std::function was overkill. But it serves two purposes.

    First, it gives you a uniform syntax for calling function objects. For example, you can use an std::function instantiation to wrap an ordinary function that takes a single argument of a class type or a member function and the class object that it should be applied to without worrying about the different calling syntax.

    struct S {
        void f();
    };
    
    void g(const S&);
    
    S obj;
    
    typedef std::function functor1(&S::f, obj);
    typedef std::function functor2(&g, obj);
    
    functor1(); // calls obj.f()
    functor2(); // calls g(obj);
    

    Note that both functors here are called with the same syntax. That's a big benefit when you're writing generic code. The decision of how to call the underlying function is made within the std::function template, and you don't have to figure it out in your code.

    The other big benefit is that you can reassign the function object that a std::function object holds:

    functor1 = std::function()>(&g, obj);
    

    This changes the behavior of functor1:

    functor1() // calls g(obj)
    

    Sometimes that matters.

提交回复
热议问题