Use of a member pointer to a member function in for_each - is it possible?

Hi, I am struggling to find the proper combination of ataptors/binders to use a member pointer to a member function in a for_each. Is this possible at all? Any help is appreciated. Here is the code: #include <iostream> #include <algorithm> #include <vector> #include <boost/bind.hpp> #include <boost/ref.hpp> using namespace std; class foo { private: int value; void default_proc(int& x) { cout << "default_proc. Value = " << value << ", Param = " << x << "\n";} void init1_proc(int& x) { cout << "init1_proc. Value = " << value << ", Param = " << x << "\n";} public: void (foo::*func_ptr)(int& x); //yes, I need the reference here foo(int init) : value(init), func_ptr(init == 1 ? &foo::init1_proc : &foo::default_proc) {} }; int main() { vector<foo> foos; foos.push_back(foo(0)); foos.push_back(foo(1)); foos.push_back(foo(2)); int param = 3; //i need this functionality: //prints "default_proc. Value = 0, Param = 3": (foos[0].*foos[0].func_ptr)(param); //prints "init1_proc. Value = 1, Param = 3": (foos[1].*foos[1].func_ptr)(param); //prints "default_proc. Value = 2, Param = 3": (foos[2].*foos[2].func_ptr)(param); //using the right combination of for_each, bind, ref, mem_fn, etc: // std::for_each(foos.begin(), foos.end(), // boost::bind(???????), // _1, boost::ref(param)); } The compiler is Borland C++ 5.6.4 for Win32. Thanks in advance

On 26 May 2004, at 11:48 PM, Vesselin Kostadinov wrote:
//using the right combination of for_each, bind, ref, mem_fn, etc: // std::for_each(foos.begin(), foos.end(), // boost::bind(???????), // _1, boost::ref(param)); }
Hmm, I don't know if you could do that directly. If you added a function to foo like such: void call_func_ptr(int &x) { this->func_ptr(x); } then you could do: std::for_each(foos.begin(), foos.end(), boost::bind(&foo::call_func_ptr, _1, boost::ref(param)); You definitely want the _1 as a parameter to boost::bind, not std::for_each. Every argument (including the "this" pointer) should be mentioned in the bind, even if only to provide the placeholder. Scott
participants (2)
-
Scott Lamb
-
Vesselin Kostadinov