std::bind 和 std::function 重叠或互补

std::bind and std::function overlap or complementary?

本文关键字:std function bind 重叠      更新时间:2023-10-16

我在这里看这个示例,结合 std::bind 和 std::function 以创建一个命令:真的很整洁!命令类的代码如下所示:

class Command
{
 private:
   std::function<void ()> _f;
 public:
   command() {}
   command(std::function<void ()> f) : _f(f) {}
   template <typename T> void setFunction (T t) {_f = t ;}
   void execute()
    {
        if(!_f.empty())
            _f();
    }
};

假设我有一个包含成员函数的类MyClass

class MyClass
{
public:
    void myMemberFn() {}
}

然后调用代码如下所示:

MyClass myClass;
command(std::bind(&MyClass::myMemberFn, myClass));

虽然我必须承认,我真的不明白为什么除了std::bind之外还需要std::function.在我看来,绑定已经封装了函数调用,那么为什么Command需要函数呢?Command不能存储std::bind而不是std::function吗?

我一直在查看标准::绑定和标准::函数的文档,但没有得到它......

有人知道为什么需要std::function吗?

PS:我假设标准::绑定~=提升::

绑定和标准::函数~=提升:函数

您必须将

std::bind表达式的结果存储在某个地方。标准未指定 std::bind 本身的返回类型,因此您无法创建该类型的命名成员变量(不过,您可以使用 C++11 auto来创建这样的局部变量!

此外,任何采用std::function的函数都可以(由于隐式转换std::function)接受各种可调用对象,而不仅仅是std::bind结果 - 您可以向其传递常规函数指针、lambda、自定义函数对象,任何可以调用的内容。

从绑定文档,

A function object of unspecified type T, for which std::is_bind_expression<T>::value == true, 
and which can be stored in std::function.

所以

std::function<void ()> _f;

需要存储 的返回值

command(std::bind(&MyClass::myMemberFn, myClass));

以便以后可以实际调用它。