Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you could write a small <code>myint</code> class which makes sure that the <code>int</code> you pass is always greater than <code>1</code>:</p> <pre><code>struct myint { int data; myint(int i) : data(i) { assert(data &gt; 1); } }; </code></pre> <p>Now use it in your class:</p> <pre><code>class B : public A{ public: B(myint dim) //this can still take int, due to implicit conversion! : A(dim.data) { } } </code></pre> <p>Note that you can still construct <code>B</code> passing <code>int</code>, as it will implicitly convert into <code>myint</code> and while the conversion takes place (implicitly), it will test the <em>assert</em>, and if that succeeds, only then you would be able to pass <code>dim.data</code> to the base class <code>A</code>. If the <em>assert</em> fails, your program will abort before entering into the base class constructor (without initializing anything in derived class also).</p> <hr> <p>You could even generalize it as:</p> <pre><code>//Summary : gint&lt;N&gt; makes sure that data &gt; N template&lt;int N&gt; struct gint //call it greater int { int data; gint(int i) : data(i) { assert(data &gt; N); } //Use N here! }; </code></pre> <p>Now use it in your class:</p> <pre><code>class B : public A{ public: B(gint&lt;1&gt; dim) //the template argument 1 makes sure that dim.data &gt; 1 : A(dim.data) { } } </code></pre> <p>If you need another class, for example:</p> <pre><code>class Xyz : public A{ public: B(gint&lt;10&gt; dim) //gint&lt;10&gt; makes sure that dim.data &gt; 10 : A(dim.data) { } } </code></pre> <p>Cool, isn't?</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