【问题标题】:mem_fun and bind1st problemmem_fun 和 bind1st 问题
【发布时间】:2023-03-30 02:54:01
【问题描述】:

我有以下课程:

class A {
public:
// ctr and etc ...
A*   clone(B* container);
};

现在,我已经填充了 vector<A*> availableObjs。我想在其中的每一个上调用clone,因此并将克隆的对象插入vector<A*> 类型的新容器clonedObjs。我正在尝试关注 - 但它无法编译:

transform(availableObjs.begin(), availableObjs.end(), back_inserter(clonedObjs),
    bind1st(mem_fun(&A::clone), container)); // container is of type B*

有没有简单的出路?我有很多像 A 一样的分类 - 所以让它们中的每一个都成为函子是太多的任务。

【问题讨论】:

标签: c++ transform mem-fun


【解决方案1】:

如果您使用 Boost.Bind,它可能如下所示:

std::transform(
               availableObjs.begin(), availableObjs.end(), 
               back_inserter(clonedObjs),
               boost::bind<A*>(boost::mem_fn(&A::clone), _1, container) ); 

【讨论】:

    【解决方案2】:

    您需要使用bind2nd 而不是bind1st

    transform(availableObjs.begin(), availableObjs.end(), back_inserter(clonedObjs),
        bind2nd(mem_fun(&A::clone), container)); // container is of type B*
    

    mem_fun(&amp;A::clone) 创建的函子需要 A* 作为其第一个参数。这是调用方法的通常隐式指定的实例。 A::clone的第一个“真实”参数是mem_fun(&amp;A::clone)的第二个参数,因此需要与bind2nd绑定。

    【讨论】:

      猜你喜欢
      • 2011-02-24
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多