C ++调用for_each中的成员函数以获取成员容器中的项目 [英] C++ To call member function in for_each for items in the member container

查看:120
本文介绍了C ++调用for_each中的成员函数以获取成员容器中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像这样的类(模仿一些STL的容器):

If I have a class (that mimic some of STL's container) like this:


class Elem {
public:
  void prepare(); // do something on *this
  // ...

};

class Selector {
public:
  typedef vector<Elem *> container_type;
  typedef container_type::iterator iterator;

  iterator begin() { return cont_.begin(); }
  iterator end() { return cont_.end(); }

  void check_all();

private:
  prepare_elem(Elem *p); // do something on 'p'
  container_type cont_;

};

如果我想为"cont_"中的所有元素调用prepare(),我可以 以下功能:

If I want to call prepare() for all elements in 'cont_', I could make the following function:


void Selector::check_all() {
  for_each(cont_.begin(), cont_.end(), mem_fun(&Elem::prepare));

}

我的问题是,如果我想调用Selector :: prepare_elem() "cont_"中的所有元素?我最初的方法无法编译:

My question is, what if I want to call Selector::prepare_elem() for all elements in 'cont_'? My initial approach won't compile:


void Selector::check_all() {
  for_each(cont_.begin(), cont_.end(),
           mem_fun(&Selector::prepare_elem));

}

第二种方法也失败了:


void Selector::check_all() {
  for_each(cont_.begin(), cont_.end(),
           bind1st(mem_fun(&Selector::prepare_elem), this));
}

是否仍然可以使用std :: for_each()进行调用 选择器:: prepare_elem()?

Is there anyway to use std::for_each() to call Selector::prepare_elem()?

如果有办法,我想知道一个没有助推的解决方案.

If there's way, I'd like to know a solution without boost.

推荐答案

如果您不想使用boost :: bind,请使用std :: tr1 :: bind.

If you don't want to use boost::bind - use std::tr1::bind.

这篇关于C ++调用for_each中的成员函数以获取成员容器中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆