【发布时间】:2020-08-21 16:31:55
【问题描述】:
为 STL 算法和容器编写比较函数很乏味。
对于像这样的简单对象,
struct Person
{
int id;
string name;
string surname;
string get_full_name(); // name then surname
};
我必须为lhs 和rhs 键入相同的函数调用:
vector<Person> v = { ... };
std::sort( v.begin(), v.end(), [](const Object &lhs, const Object &rhs) {
return lhs.get_full_name() < rhs.get_full_name(); // tedious
} );
我希望能够使用指向成员函数或指向成员数据的指针来编写比较函数/仿函数。可能是这样的:
std::sort( v.begin(), v.end(), make_compare_functor( &Object::get_full_name ));
std::sort( v.begin(), v.end(), make_compare_functor( &Object::surname ));
我试过这样实现它:
template <class R, class T>
struct CompareFunctor {
R (T::*fp)();
bool operator() (const T& lhs, const T& rhs) {
return lhs->*fp() < rhs->*fp();
}
};
// helper function
template <class R, class T>
CompareFunctor<R,T> make_compare_functor(R(T::*fp)()) {
return CompareFunctor<R,T> { fp };
}
但它无法为这些情况中的任何实例化T
auto functor1 = make_compare_functor( &Person::get_full_name );
auto functor2 = make_compare_functor( &std::string::size );
(错误信息如:'make_compare_functor': no matching overloaded function found ... note: could be 'const Person' or 'Person')
谁能指导我如何使用指向成员函数的指针来编写比较函数/仿函数?
最好是基于 STL 的 -- 没有 Boost 或其他库。
【问题讨论】:
-
没有 Boost 或其他库。 -- 好吧,如果 Boost 中有什么东西可以解决您的问题,您是否不需要简单地查看 Boost 源代码和看看他们做了什么来回答你的问题?