【问题标题】:std::rel_ops functionality as a base class. Is that appropriate solution?std::rel_ops 功能作为基类。这是合适的解决方案吗?
【发布时间】: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&amp; Base() const { return static_cast&lt;T&amp;&gt;(*this); }。如果你正在学习,你会做得很好。如果你想定义运算符,你应该看看 Boost.Operators,就像 usta 推荐的那样。
  • 如果您需要手动操作,我可能还应该建议更好的方法来定义这样的运算符:用!(rhs&lt;lhs) 定义lhs&lt;=rhs,用rhs&lt;lhs 定义lhs&gt;rhs .
  • 所有这些函数的“内联”规范是多余的,因为在类主体中定义的函数是隐式内联的。

标签: c++ templates comparison-operators


【解决方案1】:

好吧,为什么不使用Boost.Operators

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多