How to pass arguments using std :: mem_fun

I would know if there is a way to pass arguments using std :: mem_fun? I want to clarify that I can have as many arguments as possible, and many member functions.
The problem is that I am on the old standard and I am looking for a complete stl method, so boost is not allowed as an answer, even if I know I can do it easily = /

Here is a small illustration of how I want to use it:

#include <list>
#include <algorithm>

// Class declaration
//
struct Interface {
   virtual void run() = 0;
   virtual void do_something(int) = 0;
   virtual void do_func(int, int) = 0;
};

struct A : public Interface {
   void run() { cout << "Class A : run" << endl; }
   void do_something(int foo) { cout << "Class A : " << foo << endl; }
   void do_func(int foo, int bar) { cout << "Class A : " << foo << " " << bar << endl; }
};

struct B : public Interface {
   void run() { cout << "Class B : run" << endl; }
   void do_something(int foo) { cout << "Class B : " << foo << endl; }
   void do_func(int foo, int bar) { cout << "Class B : " << foo << " " << bar << endl; }
};

// Main
//
int main() {
   // Create A and B
   A a;
   B b;

   // Insert it inside a list
   std::list<Interface *> list;
   list.push_back(&a);
   list.push_back(&b);

   // This works
   std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::run));

   // But how to give arguments for those member funcs ?
   std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::do_something));
   std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::do_func));
   return 0;
}
+5
source share
3 answers

Use std::bindthrough std::bind1standstd::bind2nd

std::for_each(list.begin(), list.end(),
              std::bind2nd(std::mem_fun(&Interface::do_something),1) // because 1st is this
             );

Unfortunately, the standard does not help for the two versions of the arguments, and you need to write your own:

struct MyFunctor
{
    void (Interface::*func)(int,int);
    int         a;
    int         b;

    MyFunctor(void (Interface::*f)(int,int), int a, int b): func(f), a(a), b(b) {}

    void operator()(Interface* i){ (i->*func)(a,b);}
};

std::for_each(list.begin(), list.end(),
              MyFunctor(&Interface::do_func, 1, 2)
             );
+11
source

. std::bind1st std::bind2nd. , , , ++ 03, - , , .

: / , std::bind1st / std::bind2nd. , , (IMO) .

template<class T>
class invoke_do_something { 
    int value;
public:
    adder(int x) : value(x) {}
    void operator()(T &t) { 
        t.do_something(value);
    }
};

std::for_each(list.begin(), list.end(), invoke_do_something(1));

, . , for_each. , , , , - .

+1

You can bind:

using std::placeholders::_1
int a;
std::for_each(list.begin(), list.end(), std::bind(&Interface::do_something, _1, a));
+1
source

All Articles