I am developing several classes that must support the operators != , > , <= And >= . These operators will be implemented in terms of the == and < operators.
At this point, I need to make a choice between inheritance¹ and force my consumers to use std::rel_ops ² manually.
[1] Inheritance (possible implementation):
template<class T> class RelationalOperatorsImpl { protected: RelationalOperatorsImpl() {} ~RelationalOperatorsImpl() {} friend bool operator!=(const T& lhs, const T& rhs) {return !(lhs == rhs);} friend bool operator>(const T& lhs, const T& rhs) {return (rhs < lhs);} friend bool operator<=(const T& lhs, const T& rhs) {return !(rhs < lhs);} friend bool operator>=(const T& lhs, const T& rhs) {return !(lhs < rhs);} }; template<typename T> class Foo : RelationalOperatorsImpl< Foo<T> > { public: explicit Foo(const T& value) : m_Value(value) {} friend bool operator==(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value == rhs.m_Value);} friend bool operator<(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value < rhs.m_Value);} private: T m_Value; };
[2] std::rel_ops glue:
template<typename T> class Foo { public: explicit Foo(const T& value) : m_Value(value) {} friend bool operator==(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value == rhs.m_Value);} friend bool operator<(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value < rhs.m_Value);} private: T m_Value; }; void Consumer() { using namespace std::rel_ops;
I mainly try to avoid code repetition. Any thoughts on which method "feels" better?
GSH110
source share