Note that there are some explanatory texts on larger screens.

plurals
  1. PORelational Operator Implementation Dilemma
    text
    copied!<p>I'm in the process of designing several classes that need to support operators <code>!=</code>, <code>&gt;</code>, <code>&lt;=</code>, and <code>&gt;=</code>. These operators will be implemented in terms of operators <code>==</code> and <code>&lt;</code>.</p> <p>At this stage, I need to make a choice between inheritance¹ and forcing my consumers to use <code>std::rel_ops</code>² "manually".</p> <p>[1] Inheritance (possible implementation):</p> <pre><code>template&lt;class T&gt; class RelationalOperatorsImpl { protected: RelationalOperatorsImpl() {} ~RelationalOperatorsImpl() {} friend bool operator!=(const T&amp; lhs, const T&amp; rhs) {return !(lhs == rhs);} friend bool operator&gt;(const T&amp; lhs, const T&amp; rhs) {return (rhs &lt; lhs);} friend bool operator&lt;=(const T&amp; lhs, const T&amp; rhs) {return !(rhs &lt; lhs);} friend bool operator&gt;=(const T&amp; lhs, const T&amp; rhs) {return !(lhs &lt; rhs);} }; template&lt;typename T&gt; class Foo : RelationalOperatorsImpl&lt; Foo&lt;T&gt; &gt; { public: explicit Foo(const T&amp; value) : m_Value(value) {} friend bool operator==(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value == rhs.m_Value);} friend bool operator&lt;(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value &lt; rhs.m_Value);} private: T m_Value; }; </code></pre> <p>[2] <code>std::rel_ops</code> glue:</p> <pre><code>template&lt;typename T&gt; class Foo { public: explicit Foo(const T&amp; value) : m_Value(value) {} friend bool operator==(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value == rhs.m_Value);} friend bool operator&lt;(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value &lt; rhs.m_Value);} private: T m_Value; }; void Consumer() { using namespace std::rel_ops; //Operators !=, &gt;, &gt;=, and &lt;= will be instantiated for Foo&lt;T&gt; (in this case) on demand. } </code></pre> <p>I'm basically trying to avoid code repetition. Any thoughts as to which method "feels" better?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload