【发布时间】:2012-05-26 17:02:52
【问题描述】:
如果以前有人问过这个问题,请原谅我,我只是找不到合适的解决方案。
我经常发现自己为如下类的成员函数创建仿函数,然后用于 find_if 或 remove_if
class by_id{
public:
by_id(int id):mId(id) {}
template <class T>
bool operator()(T const& rX) const { return rX.getId() == mId; }
template <class T>
bool operator()(T* const pX) const { return (*this)(*pX); }
private:
int mId;
};
虽然这很好用,但它包含大量样板文件,并意味着为我想用于比较的每个成员函数定义一个类。
我知道 C++11 中的 lambda,但由于交叉编译器的限制,我无法切换到新标准。
我发现的最接近的相关问题是stl remove_if with class member function result,但给定的解决方案意味着添加额外的成员函数进行比较,这很难看。
难道没有更简单的方法使用标准 STL 或 boost 以更通用的方式编写此类函子或使用 bind 完全跳过它们吗?
类似通用仿函数的东西可以,但我缺乏编写它的技能。 只是为了弄清楚我的想法:
template<typename FP,typename COMP>
class by_id{
public:
by_id(COMP id):mId(id) {}
template <class T>
bool operator()(T const& rX) const { return rX.FP() == mId; }
//of course this does not work
template <class T>
bool operator()(T* const pX) const { return (*this)(*pX); }
private:
COMP mId;
};
【问题讨论】:
标签: generics boost stl functor