如何使用boost :: bind与不可复制的参数,例如boost :: promise? [英] How to use boost::bind with non-copyable params, for example boost::promise?

查看:259
本文介绍了如何使用boost :: bind与不可复制的参数,例如boost :: promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Some C++ objects have no copy constructor, but have move constructor. For example, boost::promise. How can I bind those objects using their move constructors ?

#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;
}


推荐答案

::移动。为什么不使用std :: bind,应该知道move语义?

I see that you uses std::move. Why don't you use std::bind which should be aware of move semantics?

template<class F, class... BoundArgs>
unspecified bind(F&&, BoundArgs&&...);
template<class R, class F, class... BoundArgs>
unspecified bind(F&&, BoundArgs&&...);

关于声明fullfil_1的移动版本

Wht about declaring a move version of fullfil_1

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

Boost.Bind不支持移动语义不知道)。我希望当前审查的Boost.Move将被接受,Boost.Bind,Boost.Lambda和Boost.Phoenix将添加移动语义接口。

Boost.Bind doesn't supports move semantics yet (at least I'm not aware of). I hope that the currently reviewed Boost.Move will be accepted, and that Boost.Bind, Boost.Lambda and Boost.Phoenix will add the move semantics interfaces.

你可以请尝试编写ref并移动如下

You can try composing ref and move as follows

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

这篇关于如何使用boost :: bind与不可复制的参数,例如boost :: promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆