Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using STL to bind multiple function arguments

Tags:

c++

stl

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.

like image 598
RC. Avatar asked Aug 26 '09 14:08

RC.


People also ask

What is std :: bind () in CPP?

std::bind is for partial function application. That is, suppose you have a function object f which takes 3 arguments: f(a,b,c); You want a new function object which only takes two arguments, defined as: g(a,b) := f(a, 4, b);

What does STD bind return?

std::bind. Returns a function object based on fn , but with its arguments bound to args . Each argument may either be bound to a value or be a placeholder: - If bound to a value, calling the returned function object will always use that value as argument.

What does boost bind do?

boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.

Why is it important to bind a function to its arguments C++?

Bind function with the help of placeholders helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output.


2 Answers

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.

like image 123
jalf Avatar answered Sep 24 '22 07:09

jalf


The "STL solution" would be to write your own binder... that's why they created the powerful boost::bind.

like image 27
UncleZeiv Avatar answered Sep 21 '22 07:09

UncleZeiv