C++ – Using STL to bind multiple function arguments

cstl

In the past I've used the bind1st and bind2nd functions in order to do straight forward operations on STL containers. I now have a container of MyBase class pointers that are for simplicities sake the following:

class X
{
public:
    std::string getName() const;
};

I want to call the following static function using for_each and binding both the 1st and 2nd parameters as such:

StaticFuncClass::doSomething(ptr->getName(), funcReturningString() );

How would I use for_each and bind both parameters of this function?

I'm looking for something along the lines of:

for_each(ctr.begin(), ctr.end(), 
         bind2Args(StaticFuncClass::doSomething(), 
                   mem_fun(&X::getName), 
                   funcReturningString());

I see Boost offers a bind function of its own that looks like something that would be of use here, but what is the STL solution?

Thanks in advance for your responses.

Best Answer

A reliable fallback when the bind-syntax gets too weird is to define your own functor:

struct callDoSomething {
  void operator()(const X* x){
    StaticFuncClass::doSomething(x->getName(), funcReturningString());
  }
};

for_each(ctr.begin(), ctr.end(), callDoSomething());

This is more or less what the bind functions do behind the scenes anyway.

Related Topic