Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::bind and class member function

Tags:

c++

boost-bind

Consider following example.

#include <iostream>
#include <algorithm>
#include <vector>

#include <boost/bind.hpp>

void
func(int e, int x) {
    std::cerr << "x is " << x << std::endl;
    std::cerr << "e is " << e << std::endl;
}

struct foo {
    std::vector<int> v;

    void calc(int x) {
        std::for_each(v.begin(), v.end(),
            boost::bind(func, _1, x));
    }

    void func2(int e, int x) {
        std::cerr << "x is " << x << std::endl;
        std::cerr << "e is " << e << std::endl;
    }

};

int
main()
{
    foo f;

    f.v.push_back(1);
    f.v.push_back(2);
    f.v.push_back(3);
    f.v.push_back(4);

    f.calc(1);

    return 0;
}

All works fine if I use func() function. But in real life application I have to use class member function, i.e. foo::func2() in this example. How can I do this with boost::bind ?

like image 560
Konstantin Avatar asked Jun 15 '09 10:06

Konstantin


2 Answers

You were really, really close:

void calc(int x) {
    std::for_each(v.begin(), v.end(),
        boost::bind(&foo::func2, this, _1, x));
}

EDIT: oops, so was I. heh.

Although, on reflection, there is nothing really wrong with your first working example. You should really favour free functions over member functions where possible - you can see the increased simplicity in your version.

like image 172
1800 INFORMATION Avatar answered Sep 21 '22 14:09

1800 INFORMATION


While using boost::bind for binding class member functions, the second argument must supply the object context. So your code will work when the second argument is this

like image 23
Mudit Jain Avatar answered Sep 19 '22 14:09

Mudit Jain