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

are*_*uit 2 c++ boost stl c++11

我在这里这个例子,结合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();
    }
};
Run Code Online (Sandbox Code Playgroud)

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

class MyClass
{
public:
    void myMemberFn() {}
}
Run Code Online (Sandbox Code Playgroud)

那么调用代码看起来像:

MyClass myClass;

command(std::bind(&MyClass::myMemberFn, myClass));
Run Code Online (Sandbox Code Playgroud)

虽然我必须承认我并不真正理解为什么std::function还需要std::bind.在我看来bind已经封装了函数调用,那么为什么需要函数Command呢?无法Command存储std::bind而不是std::function

我一直在查看std :: bindstd :: function的文档,但没有得到它...

任何人都知道为什么std::function需要它?

PS:我假设std :: bind~ = boost :: bind和std :: function~ = boost :: function

Joh*_*esD 6

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

此外,任何函数std::function可以(由于std::function隐式转换)接受各种可调用对象,而不仅仅是std::bind结果 - 您可以传递一个常规函数指针,一个lambda,一个自定义函数对象,无论可以调用什么.