Idiomatic use of std::rel_ops

前端 未结 4 1754
悲&欢浪女
悲&欢浪女 2020-12-08 04:24

What is the preferred method of using std::rel_ops to add the full set of relational operators to a class?

This documentation suggests a using nam

4条回答
  •  星月不相逢
    2020-12-08 05:06

    It's not the nicest, but you can use using namespace std::rel_ops as an implementation detail for implementing the comparison operators on your type. For example:

    template 
    struct MyType
    {
        T value;
    
        friend bool operator<(MyType const& lhs, MyType const& rhs)
        {
            // The type must define `operator<`; std::rel_ops doesn't do that
            return lhs.value < rhs.value;
        }
    
        friend bool operator<=(MyType const& lhs, MyType const& rhs)
        {
            using namespace std::rel_ops;
            return lhs.value <= rhs.value;
        }
    
        // ... all the other comparison operators
    };
    

    By using using namespace std::rel_ops;, we allow ADL to lookup operator<= if it is defined for the type, but fall back onto the one defined in std::rel_ops otherwise.

    This is still a pain, though, as you still have to write a function for each of the comparison operators.

提交回复
热议问题