我已将 std::rel_ops 命名空间的功能实现为模板基类(它仅使用运算符 < 和 == 定义所有比较运算符)。对我来说,它(到目前为止)正常工作有点奇怪,我也担心使用的“黑客”。任何人都可以评估以下代码并说我是幸运地工作还是这样做是标准做法。
template <typename T>
class RelationalOps {
public:
inline bool operator!=(const T &rhs) const
{
const T& lhs = static_cast<const T&>(*this);
return !(lhs == rhs);
}
inline bool operator<=(const T &rhs) const
{
const T& lhs = static_cast<const T&>(*this);
return ((lhs < rhs) || (lhs == rhs));
}
inline bool operator>(const T &rhs) const
{
const T& lhs = static_cast<const T&>(*this);
return !((lhs < rhs) || (lhs == rhs));
}
inline bool operator>=(const T &rhs) const
{
const T& lhs = static_cast<const T&>(*this);
return !(lhs < rhs);
}
};