Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A lot depends on what type of argument you imagine your clients trying to pass. If they're passing int, and that's clearly big enough to hold the range of values you're going to use, then there's no practical advantage to using std::size_t - it won't enforce anything, and the way the issue manifests as an apparently huge number is simply more confusing.</p> <p>BUT - it is good to use size_t anyway as it helps document the expectations of the API.</p> <p>You clearly can't do a compile-time check for "> 0" against a run-time generated value, but can at least disambiguate negative inputs from intentional huge numbers ala</p> <pre><code>template &lt;typename T&gt; void f(T t) { if (!(t &gt; 0)) throw std::runtime_error("be positive!"); // do stuff with t, knowing it's not -1 shoehorned into size_t... ... } </code></pre> <p>But, if you are really concerned about this, you could provide overloads:</p> <pre><code>// call me please e.g. f(size_t(10)); void f(size_t); // unimplemented (and private if possible)... // "want to make sure you realise this is unsigned: call f(size_t) explicitly void f(int32_t); void f(int64_t); </code></pre> <p>...then there's a compile-time error leading to the comments re caller explicitly providing a size_t argument (casting if necessary). Forcing the client to provide an arg of size_t type is a pretty good way to make sure they're conscious of the issue.</p> <p>Rin's got a good idea too - would work really well where it works at all (depends on there being an signed int type larger than size_t). Go check it out....</p> <p>EDIT - demonstration of template idea above...</p> <pre><code>#include &lt;iostream&gt; template &lt;typename T&gt; void f(T t) { if (!(t &gt; 0)) std::cout &lt;&lt; "bad call f(" &lt;&lt; (int)t &lt;&lt; ")\n"; else std::cout &lt;&lt; "good f(" &lt;&lt; (int)t &lt;&lt; ")\n"; } int main() { f((char)-1); f((unsigned char)255); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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