简体   繁体   English

mem_fun和bind1st问题

[英]mem_fun and bind1st problem

I've following class: 我跟着上课:

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

Now, I've a vector<A*> availableObjs populated already. 现在,我已经填充了一个vector<A*> availableObjs <A *> vector<A*> availableObjs I want to call clone on each of those, so and insert cloned objects into a new container clonedObjs of type vector<A*> . 我想在每个上调用clone ,因此将克隆的对象插入到vector<A*> clonedObjs类型的新容器clonedObjs中。 I'm trying following - but it doesn't compile: 我正在尝试跟随 - 但它不编译:

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

Is there a easy way out? 有一个简单的方法吗? I've a lot classed like A - so making each of those a functor is too much task. 我有很多被归类为A - 所以让每个人成为一个算子太多了。

You need to use bind2nd instead of bind1st : 您需要使用bind2nd而不是bind1st

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

The functor created by mem_fun(&A::clone) expects an A* as its first parameter. mem_fun(&A::clone)创建的mem_fun(&A::clone)函数需要A*作为其第一个参数。 This is the normally implicitly specified instance on which the method is called. 这是通常隐式指定的实例,在该实例上调用该方法。 The first "real" parameter of A::clone is the second parameter of mem_fun(&A::clone) and therefore needs to be bound with bind2nd . A::clone的第一个“真实”参数是mem_fun(&A::clone)的第二个参数,因此需要与bind2nd绑定。

If you use Boost.Bind it might look like this: 如果您使用Boost.Bind,它可能如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM