mem_fun and bind1st problem
Asked Answered
S

2

2

I've following class:

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

Now, I've a vector<A*> availableObjs populated already. I want to call clone on each of those, so and insert cloned objects into a new container clonedObjs of type vector<A*>. 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.

Suprasegmental answered 19/11, 2009 at 11:52 Comment(1)
Are you sure you want to have pointers in your container? You must not call any modifying algorithm on that algorithm (like for example sort). However, you could use a vector of shared_ptr<A*>, then you support value semantics again.Castiglione
P
12

You need to use bind2nd instead of 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. 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.

Pillage answered 19/11, 2009 at 12:13 Comment(0)
M
2

If you use Boost.Bind it might look like this:

std::transform(
               availableObjs.begin(), availableObjs.end(), 
               back_inserter(clonedObjs),
               boost::bind<A*>(boost::mem_fn(&A::clone), _1, container) ); 
Meng answered 19/11, 2009 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.