Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Why assert? If your compiler's shift operator doesn't suit your needs, you could gracefully remedy the situation by sign-extending the result. Also, sometimes run-time is good enough. After all, the compiler's optimizer can make compile-time out of run-time:</p> <pre><code>template &lt;typename Number&gt; inline Number shift_logical_right(Number value, size_t bits) { static const bool shift_is_arithmetic = (Number(-1) &gt;&gt; 1) == Number(-1); const bool negative = value &lt; 0; value &gt;&gt;= bits; if (!shift_is_arithmetic &amp;&amp; negative) // sign extend value |= -(Number(1) &lt;&lt; (sizeof(Number) * 8 - bits)); } </code></pre> <p>The <code>static const bool</code> can be evaluated at compile time, so if <code>shift_is_arithmetic</code> is guaranteed to be <code>true</code>, every compiler worth its salt will eliminate the whole <code>if</code> clause and the construction of <code>const bool negative</code> as dead code.</p> <p>Note: code is adapted from Mono's <code>encode_sleb128</code> function: <a href="https://github.com/mono/mono/blob/master/mono/profiler/utils.c" rel="nofollow">here</a>.</p> <p><strong>Update</strong></p> <p>If you really want to abort compilation on machines without arithmetic shift, you're still better off not relying on the preprocessor. You can use <code>static_assert</code> (or <code>BOOST_STATIC_ASSERT</code>):</p> <pre><code>static_assert((Number(-1) &gt;&gt; 1) == Number(-1), "Arithmetic shift unsupported."); </code></pre>
 

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