2009-06-15 78 views
15

请考虑以下示例。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; 
} 

所有,如果我使用func()功能工作正常。但在现实生活中,我必须使用类成员函数,例如foo::func2()。我如何用boost :: bind做到这一点?

回答

18

你真的,真的非常接近:

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

编辑:哎呀,我也是。嘿。

虽然经过反思,您的第一个工作示例没有任何问题。您应该尽可能地在成员函数上使用免费函数 - 您可以在版本中看到增加的简单性。

+0

这应该与boost :: lamba :: bind一起使用。我没有使用boost :: bind很多。 – 2009-06-15 10:17:05

1

使用boost :: bind绑定类成员函数时,第二个参数必须提供对象上下文。所以你的代码将工作时,第二个参数是this

相关问题