Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's a very common problem indeed, last time I saw it was with matrices (dimensions as template parameters and how to deal with runtime supplied value).</p> <p>It's unfortunately an intractable problem.</p> <p>The issue is not specific to C++ per se, it's specific to strong typing coupled with compile-time checking. For example Haskell could exhibit a similar behavior.</p> <p>There are 2 ways to deal with this:</p> <ul> <li>You use a <code>switch</code> not to create the type but actually to launch the full computation, ie <code>main</code> is almost empty and only serve to read the input value</li> <li>You use boxing: you put the actual type in a generic container (either by hand-crafted class or <code>boost::any</code> or <code>boost::variant</code>) and then, when necessary, unbox the value for specific treatment.</li> </ul> <p>I personally prefer the second approach.</p> <p>The easier way to do this is to use a base class (interface):</p> <pre><code>struct UnsignedBase: boost::noncopyable { virtual ~UnsignedBase() {} virtual UnsignedBase* clone() const = 0; virtual size_t bytes() const = 0; virtual void add(UnsignedBase const&amp; rhs) = 0; virtual void substract(UnsignedBase const&amp; rhs) = 0; }; </code></pre> <p>Then you wrap this class in a simple manager to ease memory management for clients (you hide the fact that you rely on heap allocation + <code>unique_ptr</code>):</p> <pre><code>class UnsignedBox { public: explicit UnsignedBox(std::string const&amp; integer); template &lt;size_t N&gt; explicit UnsignedBox(Unsigned&lt;N&gt; const&amp; integer); size_t bytes() const { return mData-&gt;bytes(); } void add(UnsignedBox const&amp; rhs) { mData-&gt;add(rhs.mData); } void substract(UnsignedBox const&amp; rhs) { mData-&gt;substract(rhs.mData); } private: std::unique_ptr&lt;UnsignedBase&gt; mData; }; </code></pre> <p>Here, the virtual dispatch takes care of unboxing (somewhat), you can also unbox manually using a <code>dynamic_cast</code> (or static_cast if you know the number of digits):</p> <pre><code>void func(UnsignedBase* i) { if (Unsigned&lt;2&gt;* ptr = dynamic_cast&lt; Unsigned&lt;2&gt; &gt;(i)) { } else if (Unsigned&lt;4&gt;* ptr = dynamic_cast&lt; Unsigned&lt;4&gt; &gt;(i)) { } // ... else { throw UnableToProceed(i); } } </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