boost :: bind和类成员函数

Kon*_*tin 15 c++ boost-bind

考虑以下示例.

#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;
}
Run Code Online (Sandbox Code Playgroud)

如果我使用func()功能,一切正常.但在现实生活中,我必须使用类成员函数,即foo::func2()在这个例子中.我怎么能用boost :: bind做到这一点?

180*_*ION 18

你真的非常非常接近:

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

编辑:哎呀,我也是.

虽然,经过反思,你的第一个工作实例并没有什么问题.在可能的情况下,您应该更喜欢免费功能而不是成员函数 - 您可以看到版本中增加的简单性.