【发布时间】:2011-04-25 06:46:37
【问题描述】:
我已将 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);
}
};
【问题讨论】:
-
您正在使用 C++ 习惯用法,称为奇怪重复模板模式 (CRTP)。这是我自己多次使用过的强大方法。有时使用特殊方法对 T 进行引用:
T& Base() const { return static_cast<T&>(*this); }。如果你正在学习,你会做得很好。如果你想定义运算符,你应该看看 Boost.Operators,就像 usta 推荐的那样。 -
如果您需要手动操作,我可能还应该建议更好的方法来定义这样的运算符:用
!(rhs<lhs)定义lhs<=rhs,用rhs<lhs定义lhs>rhs. -
所有这些函数的“内联”规范是多余的,因为在类主体中定义的函数是隐式内联的。
标签: c++ templates comparison-operators