Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>std::numeric_limits&lt;int&gt;::is_modulo</code> is a compile time constant. so you can use it for template specialization. problem solved, at least if compiler plays along with inlining.</p> <pre><code>#include &lt;limits&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #ifdef TESTING_SF bool const testing_sf = true; #else bool const testing_sf = false; #endif // C++ "extensions" namespace cppx { using std::runtime_error; using std::string; inline bool hopefully( bool const c ) { return c; } inline bool throw_x( string const&amp; s ) { throw runtime_error( s ); } } // namespace cppx // C++ "portability perversions" namespace cppp { using cppx::hopefully; using cppx::throw_x; using std::numeric_limits; namespace detail { template&lt; bool isTwosComplement &gt; int signed_from( unsigned const n ) { if( n &lt;= unsigned( numeric_limits&lt;int&gt;::max() ) ) { return static_cast&lt;int&gt;( n ); } unsigned const u_max = unsigned( -1 ); unsigned const u_half = u_max/2 + 1; if( n == u_half ) { throw_x( "signed_from: unsupported value (negative max)" ); } int const i_quarter = static_cast&lt;int&gt;( u_half/2 ); int const int_n1 = static_cast&lt;int&gt;( n - u_half ); int const int_n2 = int_n1 - i_quarter; int const int_n3 = int_n2 - i_quarter; hopefully( n == static_cast&lt;unsigned&gt;( int_n3 ) ) || throw_x( "signed_from: range error" ); return int_n3; } template&lt;&gt; inline int signed_from&lt;true&gt;( unsigned const n ) { return static_cast&lt;int&gt;( n ); } } // namespace detail inline int signed_from( unsigned const n ) { bool const is_modulo = numeric_limits&lt; int &gt;::is_modulo; return detail::signed_from&lt; is_modulo &amp;&amp; !testing_sf &gt;( n ); } } // namespace cppp #include &lt;iostream&gt; using namespace std; int main() { int const x = cppp::signed_from( -42u ); wcout &lt;&lt; x &lt;&lt; endl; } </code></pre> <p><hr> <strong>EDIT</strong>: Fixed up code to avoid possible trap on non-modular-int machines (only one is known to exist, namely the archaically configured versions of the Unisys Clearpath). For simplicity this is done by not supporting the value -2<sup><i>n</i>-1</sup> where <i>n</i> is the number of <code>int</code> value bits, on such machine (i.e., on the Clearpath). in practice this value will not be supported by the machine either (i.e., with sign-and-magnitude or 1&rsquo;s complement representation).</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