【问题标题】:Using boost::bind and boost::lambda::new_ptr to return a shared_ptr constructor使用 boost::bind 和 boost::lambda::new_ptr 返回一个 shared_ptr 构造函数
【发布时间】:2010-09-06 15:08:08
【问题描述】:

给定一个 A 类,

class A {
 public:
  A(B&) {}
};

我需要一个boost::function<boost::shared_ptr<A>(B&)> 对象。

我不想创建临时函数

boost::shared_ptr<A> foo(B& b) {
  return boost::shared_ptr<A>(new A(b));
}

为了解决我的问题,我正在尝试通过绑定 lambda::new_ptr 来解决它。

boost::function<boost::shared_ptr<A> (B&)> myFun
= boost::bind(
    boost::type<boost::shared_ptr<A> >(),
    boost::lambda::constructor<boost::shared_ptr<A> >(),
    boost::bind(
      boost::type<A*>(),
      boost::lambda::new_ptr<A>(),
      _1));

也就是说,我分两步绑定A的new_ptr和shared_ptr的构造函数。显然它不起作用:

/usr/include/boost/bind/bind.hpp:236: error: no match for call to ‘(boost::lambda::constructor<boost::shared_ptr<A> >) (A*)’
/usr/include/boost/lambda/construct.hpp:28: note: candidates are: T boost::lambda::constructor<T>::operator()() const [with T = boost::shared_ptr<A>]
/usr/include/boost/lambda/construct.hpp:33: note:                 T boost::lambda::constructor<T>::operator()(A1&) const [with A1 = A*, T = boost::shared_ptr<A>]

我应该如何进行绑定? 提前致谢, 弗朗切斯科

【问题讨论】:

  • 这是一个完美的例子,说明 lambda 实际上如何使整个事情变得不必要地复杂化,除了增加编译时间之外没有其他好处。 C++ 的极限可能被推得太远了。

标签: c++ boost boost-bind


【解决方案1】:

使用boost::lambda::bind 而不是boost::bind

#include <boost/shared_ptr.hpp>
#include <boost/lambda/bind.hpp> // !
#include <boost/lambda/construct.hpp>
#include <boost/function.hpp>

void test()
{
  using namespace boost::lambda;
  boost::function<boost::shared_ptr<A>(B&)> func = 
    bind( constructor< boost::shared_ptr<A> >(), bind( new_ptr<A>(), _1 ) );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 2023-04-03
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多