Boost logo

Boost Users :

From: Vesselin Kostadinov (Vesselin.Kostadinov_at_[hidden])
Date: 2004-05-26 23:48:09


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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net