开发者

Calling a member function with member data by using for_each

Dear all, I would like to call a member function (that expects a reference) for each object of (let's say) a vector that is a member of the same class, as the following code shows:

#include <functional>  
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

struct Stuff {
  double x;
};

class Test {
public:
  void f1(Stuff & thing);
  void f2(void);
  vector<Stuff>开发者_C百科 things;
};

void Test::f1(Stuff & thing) {
  ; // do nothing
}

void Test::f2(void) {
  for_each(things.begin(), things.end(), f1);
}

int main(void)
{

  return 0;
}  

This codes gives me a compiler error related to unresolved overloaded function type . I have tried also with bind, but it seems that the references requisite in f1 is one problem. I know I am missing something important here, so I take this opportunity to solve my problem and to learn. At the moment, I can't install boost, but I would like to know also if boost is useful to solve this problem. Thanks in advance.


  • The function you want to call cannot be simply identified by f1 but should be referred to as &Test::f1 (as in : member function f1 of class Test)
  • Function f1 does not take a single argument : as any non-static member function it has an implicit this parameter of type Test * const
  • Finally, a standard bind won't be able to do the trick because it doesn't handle parameters passed by reference.

Boost.Bind would indeed be a great option :

std::for_each(things.begin(), things.end(), boost::bind(&Test::f1, this, _1));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜