Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling literal zero in unit-safe code
    text
    copied!<p>With a very few exceptions (looking at you, Fahrenheit and Celsius temperature scales), units are linear, and the value zero is simultaneously the additive identity for all units at once.</p> <p>So given</p> <pre><code>auto speed = dimensioned(20, _meter/_second); auto power = dimensioned(75, _watt); </code></pre> <p>then</p> <pre><code>if (speed &lt; 6) ... if (power &gt; 17) ... </code></pre> <p>makes no more sense than</p> <pre><code>if (speed &gt; power) ... </code></pre> <p>you should write</p> <pre><code>if (speed &lt; dimensioned(6, _mile/_hour)) ... </code></pre> <p>However, this DOES make sense:</p> <pre><code>if (speed &lt; 0) </code></pre> <p>because 0 m/s == 0 mph == 0 A.U./fortnight or any other units that you care to use (for velocity). The question then is how to enable this and only this usage.</p> <p>C++11 explicit operators and contextual conversion to <code>bool</code> got rid of the need of the "safe-bool" idiom. It appears this problem can be solved with a comparable "safe-zero" idiom:</p> <pre><code>struct X { int a; friend bool operator&lt;(const X&amp; left, const X&amp; right) { return left.a &lt; right.a; } private: struct safe_zero_idiom; public: friend bool operator&lt;(const X&amp; left, safe_zero_idiom*) { return left.a &lt; 0; } }; </code></pre> <ul> <li>Demo: <a href="http://ideone.com/vUxmxi" rel="noreferrer">http://ideone.com/vUxmxi</a></li> </ul> <p>Unfortunately it seems that deployed dimension/unit libraries aren't doing this. (This question arose because I actually wanted to test whether a <code>std::chrono::duration</code> was negative). Is this useful? Are there cases that would cause it to fail? Is there any easier way to permit comparison to zero?</p> <p>One suspects that instead of implementing this for individual operators, there ought to exist an implicit conversion from literal zero to unit-tagged types.</p> <hr> <p>I do note that it allows</p> <pre><code> X{1} &lt; nullptr </code></pre> <p>as a valid expression :(, and unfortunately providing an inaccessible overload of type <code>std::nullptr_t</code> doesn't fix this, since the Standard says in section 4.10</p> <blockquote> <p>A null pointer constant of integral type can be converted to a prvalue of type <code>std::nullptr_t</code>.</p> </blockquote>
 

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