在C ++中这个绑定发生了什么?

时间:2016-09-09 17:45:51

标签: c++ function boost-bind stdbind

我知道这是一个简单的代码,但我无法在项目的任何地方或C ++的绑定中找到非常详细的文档。这是代码:

myv.do_safely([](auto& vec) { 
  // do something with the vector
  return true;  // or anything you like
});

我只使用了绑定一个参数而不是绑定函数,而不是两个。此外,uri.canonize(bind(&FaceController::onCanonizeSuccess, this, _1, onSuccess, onFailure, uri), bind(&FaceController::onCanonizeFailure, this, _1, onSuccess, onFailure, uri), m_ioService, TIME_ALLOWED_FOR_CANONIZATION); 具有此功能签名:

uri.canonize

在兔子洞的更远处,void FaceUri::canonize(const CanonizeSuccessCallback& onSuccess, const CanonizeFailureCallback& onFailure, boost::asio::io_service& io, const time::nanoseconds& timeout) const onSuccess 用一个参数调用,但我认为它不重要在这里展示所有。最后,onFailure的函数签名是:

onCanonizeSuccess

我真的只是要求有人向我解释这一点。这是我所理解的: void FaceController::onCanonizeSuccess(const FaceUri& uri, const CommandSuccessCallback& onSuccess, const CommandFailureCallback& onFailure, const FaceUri& request) 正在传递4个参数:

  1. 绑定函数,返回类型为uri.canonize,第一个arg绑定到FaceController::onCanonizeSuccess对象,第二个arg传递给绑定函数,然后uri,{ {1}}和onSuccess
  2. 与上面类似的绑定函数,但返回类型为onFailure
  3. uri
  4. FaceController::onCanonizeFailure
  5. 所以这意味着m_ioService这里传递了两个函数对象,每个函数对象都有一个参数,还有另外两个。然后,当TIME_ALLOWED_FOR_CANONIZATION最终使用该一个参数调用其FaceUri::canonize时,由于该函数对象绑定到返回类型FaceUri::canonize,因此该函数将被调用。

    这是我理解这里发生的事情的最佳尝试。唯一的问题是onSuccess不是绑定函数。它不可能,因为这里的arity意味着我们使用返回类型调用FaceController::onCanonizeSuccess,并且FaceController::onCanonizeSuccess是要绑定的函数。在这种情况下,bind是什么?最顶级的呼叫功能? thisthis?这一切都像泥一样清晰。不幸的是,我不知道我们正在使用哪个绑定,但我相信它是std :: bind,因为我看到一个使用std :: bind的一些包括起来。

1 个答案:

答案 0 :(得分:1)

所以, void FaceUri::canonize是一个被调用的函数。它接受四个参数,即(具有适当的cv和ref限定符)
CanonizeSuccessCallback - 一个被调用的函数(从名称猜测,成功时)
CanonizeFailureCallback - 一个被调用的函数(从名称猜测,失败时)
你可能理解这两个简单的论点。

现在,Canonize*Callback可能是对象(猜测模板),它们假设在其上定义了适当的operator()。我想你知道std::bind背后的基础知识。

uri.canonize函数调用,其中前两个参数是函数,当canonizing成功或失败时调用。

根据onCanonizeSuccess singature,您必须为该函数传递四个参数std::bind。好吧,实际上,由于该函数不是静态的,它需要第五个(或者说是第null个)类型FaceController*的参数,在该参数上应该调用函数(onCanonizeSuccess)。

bind(
  &FaceController::onCanonizeSuccess, // non-static member function requiring first argument to be pointer to FaceController instance
  this, // pointer to FaceController instance, that means, the object with function, where uri.canonize is called.
  _1, // actually std::placeholders::_1, meaning, that first argument will be passed when calling bound function                                                                                                             
  onSuccess, // rest of parameters
  onFailure,
  uri
) 
相关问题