我想知道和OP一样的事情,偶然发现了这个问题。阅读答案后,我受到 janm 和 RnR 的启发,编写了一个lexicographicalMemberCompare
仅operator<
在比较成员上使用的模板函数。它还使用boost::tuple以便您可以指定任意数量的成员。这里是:
#include <iostream>
#include <string>
#include <boost/tuple/tuple.hpp>
template <class T, class Cons>
struct LessThan
{
static bool compare(const T& lhs, const T& rhs, const Cons& cons)
{
typedef LessThan<T, typename Cons::tail_type> NextLessThan;
typename Cons::head_type memberPtr = cons.get_head();
return lhs.*memberPtr < rhs.*memberPtr ?
true :
(rhs.*memberPtr < lhs.*memberPtr ?
false :
NextLessThan::compare(lhs, rhs, cons.get_tail()));
}
};
template <class T>
struct LessThan<T, class boost::tuples::null_type>
{
static bool compare(const T& lhs, const T& rhs,
const boost::tuples::null_type& cons)
{
return false;
}
};
template <class T, class Tuple>
bool lexicographicalMemberCompare(const T& lhs, const T& rhs,
const Tuple& tuple)
{
return LessThan<T, typename Tuple::inherited>::compare(lhs, rhs, tuple);
}
struct Car
{
std::string make;
std::string model;
int year;
};
bool carLessThanCompare(const Car& lhs, const Car& rhs)
{
return lexicographicalMemberCompare(lhs, rhs,
boost::tuples::make_tuple(&Car::make, &Car::model, &Car::year));
}
int main()
{
Car car1 = {"Ford", "F150", 2009};
Car car2 = {"Ford", "Escort", 2009};
std::cout << carLessThanCompare(car1, car2) << std::endl;
std::cout << carLessThanCompare(car2, car1) << std::endl;
return 0;
}
希望这对某人有用。