开发者

Adaptors for pointer to member fields

Is there a STL method/boost class such as:

template<class S, class T>
class mem_mem : std::unary_function<T, S>
{
public:
  mem开发者_如何学Python_mem(S T::*_m) : m(_m) {}
  S operator()(T &t) const {
    return t .* m;
  }
  const S operator()(const T &t) const {
    return t .* m;
  }
private:
  S T::*m;
};

It is similar to mem_fun but for fields.


You can use boost::bind or boost::mem_fn for this. If the member passed in is a member to a field, boost::bind acts as a functor that returns the data member.

#include <vector>
#include <boost/bind.hpp>
#include <iostream>
#include <iterator>


struct X {
  X(): a(0) {};
  X(int i) : a(i) {};


  int a;
};


int main() {

  std::vector<X> v1;
  v1.reserve(10);
  for(int i = 0; i < 10; ++i) {
    v1.push_back(X(i));
  }

  std::vector<int> v2(10);
  std::transform(v1.begin(), v1.end(), v2.begin(), boost::bind(&X::a, _1));
  // or std::transform(v1.begin(), v1.end(), v2.begin(), boost::mem_fn(&X::a));
  std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout,",") );
  std::cout << std::endl;
}


boost::bind has mem_fn which looks like what you are interested in.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜