如何将boost :: bind与不可复制的params一起使用,例如boost :: promise?

use*_*202 10 c++ boost-bind boost-thread boost-function

有些C++对象没有复制构造函数,但有移动构造函数.例如,boost :: promise.如何使用移动构造函数绑定这些对象?

#include <boost/thread.hpp>

void fullfil_1(boost::promise<int>& prom, int x)
{
  prom.set_value(x);
}

boost::function<void()> get_functor() 
{
  // boost::promise is not copyable, but movable
  boost::promise<int> pi;

  // compilation error
  boost::function<void()> f_set_one = boost::bind(&fullfil_1, pi, 1);

  // compilation error as well
  boost::function<void()> f_set_one = boost::bind(&fullfil_1, std::move(pi), 1);

  // PS. I know, it is possible to bind a pointer to the object instead of 
  // the object  itself. But it is weird solution, in this case I will have
  // to take cake about lifetime of the object instead of delegating that to
  // boost::bind (by moving object into boost::function object)
  //
  // weird: pi will be destroyed on leaving the scope
  boost::function<void()> f_set_one = boost::bind(&fullfil_1, boost::ref(pi), 1);
  return f_set_one;
}
Run Code Online (Sandbox Code Playgroud)

swe*_*rup 5

我不确定如何使用移动构造函数,但是另一种方法是使用boost :: ref创建对对象的可复制引用,然后可以将其传递给boost :: bind。


Vic*_*iba 5

我看到你使用std :: move.为什么不使用应该知道移动语义的std :: bind?

template<class F, class... BoundArgs>
unspecified bind(F&&, BoundArgs&&...);
template<class R, class F, class... BoundArgs>
unspecified bind(F&&, BoundArgs&&...);
Run Code Online (Sandbox Code Playgroud)

关于宣布fullfil_1的移动版本

void fullfil_1(boost::promise<int>&é prom, int x)
{
  prom.set_value(x);
}
Run Code Online (Sandbox Code Playgroud)

Boost.Bind还不支持移动语义(至少我不知道).我希望当前评论的Boost.Move将被接受,Boost.Bind,Boost.Lambda和Boost.Phoenix将添加移动语义接口.

您可以尝试编写ref并按如下方式移动

boost::function<void()> f_set_one = boost::bind(&fullfil_1, boost::ref(std::move(pi)), 1);
Run Code Online (Sandbox Code Playgroud)