    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: CheckedInt: A Policy-Based Range-Checked Integer</title>
        <link>https://members.accu.org/index.php/journals/324</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #58 - Dec 2003 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c154/">58</a>
                    (8)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c154-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c154+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;CheckedInt: A Policy-Based Range-Checked Integer</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2003 21:55:55 +00:00 or Tue, 02 December 2003 21:55:55 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>Recently, I wanted a short example to show the canonical form
for operators on value classes. In other words, I wanted to show
how post-increment should be related to pre-increment, how
<tt class="function">operator+=</tt> and <tt class=
"function">operator+</tt> fit together, which functions should be
members and which not, and so on. Having also been reading
Alexandrescu's excellent book <i class="citetitle">Modern C++
Design</i>, I decided to make this exercise a little more
interesting (for me and for the students) by incorporating
something about policies and generic programming. What came out was
a small rangechecked integer type called <tt class=
"classname">CheckedInt</tt>. Although nothing remarkable, it turns
out to be both flexible and useful, and something that in
retrospect I could have used myself on several occasions.</p>
<p>For those who are not so familiar with operators, this class
shows how all of the arithmetic operators can (or maybe even
should) be implemented in terms of one fundamental operation:
<tt class="function">operator+=</tt>. This ensures consistency
between operators, thereby avoiding potential surprising arithmetic
inconsistencies. (For reasons of space, I show only the
addition-based operations. Implementation of the others is left, in
time-honoured fashion, to you, Gentle Reader&trade;.)</p>
<p>For those already familiar with operators, the policy aspect is
more interesting. What should happen when you try to take a
range-checked integer or enum out of its defined range or even just
modify it? For our range-checked integer, a number of possibilities
sprang to mind:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>allow silent overflow</p>
</li>
<li>
<p>throw an exception</p>
</li>
<li>
<p>saturate at the limit value</p>
</li>
<li>
<p>saturate at the limit and log the event</p>
</li>
<li>
<p>wrap around using modular arithmetic</p>
</li>
<li>
<p>log the event for debugging purposes</p>
</li>
<li>
<p>etc.</p>
</li>
</ul>
</div>
<p>This little class template allows us to choose which behaviour
we want by means of a policy class. Allowing silent overflow is the
default for integers so there's no need to write a class for that.
Throwing an exception when straying from the promised range is
possibly indicative of a programming error. Saturating at the limit
could be useful for a digital volume control; one that sticks
tenaciously to 10 when you try to set it to 11. And wrapping around
is very useful when dealing with ring buffers, dates, etc.</p>
<p>This is a simple example of feature-driven modelling and domain
analysis, as described in <i class="citetitle">Generative
Programming and Multi- Paradigm Design for C++</i> where families
of types are created with variations described in policies.</p>
<p>So, here's the abbreviated code:</p>
<pre class="programlisting">
template &lt;int low, int high&gt;
class OutOfBoundsThrower {
public:
  static int RangeCheck(int newVal) {
    if(newVal &lt; low || newVal &gt; high)
      throw std::out_of_range(&quot;RangeCheck failed&quot;);
    return newVal;
  }
};

template &lt;int low, int high&gt;
class ModularArithmetic {
public:
  static int RangeCheck(int newVal) {
    while(newVal &gt; high)
      newVal -= high - low;
    while(newVal &lt; low)
      newVal += high - low;
    return newVal;
  }
};

template &lt;int low, int high&gt;
class SaturatedArithmetic {
public:
  static int RangeCheck(int newVal) {
    if(newVal &gt; high)
      newVal = high;
    else if(newVal &lt; low)
      newVal = low;
    return newVal;
  }
};

template &lt;int low, int high,
    template &lt;int, int&gt;
    class ValueChecker = OutOfBoundsThrower&gt;
class CheckedInt :
           protected ValueChecker&lt;low, high&gt; {
  int value;

public:
  explicit CheckedInt(int i = low) :
    value(RangeCheck(i)) {}
  CheckedInt&amp; operator+=(int incr) {
    value = RangeCheck(value + incr);
    return *this;
  }

  CheckedInt&amp; operator++() {
    *this += 1;
    return *this;
  }

  const CheckedInt operator++(int) {
    CheckedInt temp(*this);
    ++*this;
    return temp;
  }

  CheckedInt&amp; operator-=(int incr) {
    *this += - incr;
    return *this;
  }

  operator int() const {
    return value;
  }

  CheckedInt&amp; operator=(int i) {
    value = RangeCheck(i);
    return *this;
  }

  const CheckedInt operator+(
          const CheckedInt&amp; other) const {
    return CheckedInt(*this) += other;
  }
};
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e76" id="d0e76"></a>Construction
and Member Functions</h2>
</div>
<p>Note that the constructor is, like most single argument
constructors, marked as <tt class="function">explicit</tt>. This is
to avoid implicit conversions that muddy the type system. Consider
what would happen with <tt class=
"function">CheckedInt&lt;0,10&gt;(5) + 27</tt> if <tt class=
"constant">27</tt> could be explicitly converted. What should its
template parameters be? Should it throw an exception? An explicit
constructor avoids these problems and forces us to state what we
want to happen. The explicit nature of object creation is
particularly useful when we wish to constrain the underlying int to
a given range as we do not want to create erroneous values. Some
might bemoan the inability to write <tt class=
"function">CheckedInt&lt;0,10&gt; ci = 5;</tt> but I think that
safety is more important than ease this time. Choosing <i class=
"parameter"><tt>low</tt></i> as the default parameter is purely
arbitrary and it is arguable that we should force the user to give
an initial value anyway.</p>
<p>When going in the opposite direction, i.e. from a <tt class=
"classname">CheckedInt</tt> to an <span class="type">int</span>,
there is no danger of breaking any constraints so we can safely use
a user-defined conversion - <tt class="function">operator
int()</tt> - so that <tt class="classname">CheckedInt</tt> appears
in a read-only context to behave like an <span class=
"type">int</span>. This allows us to use all of the existing
infrastructure for ints such as <tt class=
"function">operator&lt;&lt;</tt>, <tt class=
"function">operator==</tt>, <tt class="function">operator&lt;</tt>,
etc. We can now do things like <tt class=
"function">CheckedInt&lt;0,10&gt;(5) + 27</tt> with impunity and no
fear of exceptions.</p>
<p>One small fly swims in the ointment of <tt class=
"function">operator+=</tt>. There is the possibility that the
expression <tt class="function">value + incr</tt> might overflow
causing undefined behaviour. This would cause an unexpected problem
with saturated arithmetic if someone tried to add a very large
number to an instance that was already at its upper limit.
Alternative implementations, such as templating the underlying
arithmetic type, are possible but more complex.</p>
<p>The more astute of you might have noticed that <tt class=
"function">operator+</tt> is unusual: it is a member and it is
<tt class="function">const</tt>. The normal advice is to make
<tt class="function">operator+</tt> a non-member to allow for
implicit conversion of the left-hand operand. However, since we
have specifically disallowed that conversion there is no reason not
to make it a member and save ourselves a lot of typing! We also
return a <tt class="function">const</tt> value to prevent
modification of a temporary whilst still allowing it to be bound to
a reference.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e147" id="d0e147"></a>Templates
Versus Object-Oriented Interfaces</h2>
</div>
<p>An interesting difference in style arises with generic
programming rather than a more traditional object-oriented
approach. With O-O, one usually ends up with an interface that is
the union of all of the sub-interfaces, whereas with a templated
version the interface is usually minimal and the intersection of
features. This is primarily because with an O-O interface you can
combine only those things that you design <span class=
"emphasis"><em>a priori</em></span> to be combinable, i.e. they
must implement all of the stated interface, which can lead to a lot
of clutter and &quot;just in case&quot; methods. With templates, you can
combine anything that works <span class="emphasis"><em>a
posteriori</em></span>. Thus, templates provide compile-time
signaturebased polymorphism in a manner more reminiscent of
Smalltalk than the &quot;one size fits all&quot; of Java interfaces or C++
abstract base classes.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e158" id="d0e158"></a>Inheritance
Versus Delegation</h2>
</div>
<p>Here I have inherited from the policy class rather than
delegating to it. Altering the class to use delegation instead:</p>
<pre class="programlisting">
template &lt;int low, int high,
    class VC = OutOfBoundsThrower&lt;low,high&gt; &gt;
class CheckedInt {
public:
  explicit CheckedInt(int i = low) :
                value(VC::RangeCheck(i)) {}
</pre>
<p>moves us towards a traits-style approach, which some might
consider to be cleaner. It is also more digestible by older
compilers. In this case because the policy has no state of its own
- it is just a wrapper for a function - there is little to choose
between the two approaches. The <tt class=
"classname">ValueChecker</tt> in effect is a compile-time functor
analogous to a combination of <tt class="function">bind2nd()</tt>,
<tt class="function">logical_or()</tt>, <tt class=
"function">less&lt;int&gt;()</tt> and <tt class=
"function">greater&lt;int&gt;()</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e182" id="d0e182"></a>Legacy
Compilers and Binding-Time Issues</h2>
</div>
<p>Those of us who have to tiptoe around non-standard or ancient
compilers will know that template template parameters are off
limits. So, how can we adapt <tt class="classname">CheckedInt</tt>
to be usable? One way is to pass <i class=
"parameter"><tt>low</tt></i> and <i class=
"parameter"><tt>high</tt></i> to the <tt class=
"function">RangeCheck</tt> function at run-time. This has the nice
effect of making <tt class="classname">ValueChecker</tt> a
non-templated class and thereby eliminating some of the compilation
problems. Another would be to have a static member of the class
that held a pointer to a free function to do the range check. This
implementation would also allow the policy to be changed at
run-time, turning the class into a classic run-time version of
Strategy pattern rather than a compile-time version.</p>
<p>What we are doing is making binding-time choices. By delaying
binding from compile time to run time we trade efficiency for the
ability to use simpler constructs. We can even change the
parameters, so that we could alter the valid range of an object.
Whether we wish to do this depends on requirements. As more
programmers begin to understand the parallels between different C++
mechanisms and as compilers get better, I believe that we will see
binding time become a major design topic, leading people into both
feature-driven modelling and domain analysis.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e204" id="d0e204"></a>Extensions
and Additions</h2>
</div>
<p>Possible extensions include making the underlying type a
template parameter, as well as extending the <tt class=
"function">RangeCheck</tt> function to take the original value as a
run-time parameter as well. This would allow us to implement
propagating NaN (not a number) behaviour, where if the new value is
outside the range we set the value to an out-of-bounds value and
keep it there. This is a little bit like the effect of
floating-point NaNs which propagate &quot;NaNness&quot; into the results of
any calculation.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e212" id="d0e212"></a>Summary</h2>
</div>
<p>I hope this little class template is both useful and
instructive. It raises a number of common design issues -
relationships between operators, implicit v. explicit conversions -
and some others - binding times, policies, implicit v. explicit
interfaces, etc - that are less widespread but which I believe will
become increasingly common with time. If anyone uses <tt class=
"classname">CheckedInt</tt>, particularly with policies other than
these, I would be most interested to hear your experiences.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e220" id=
"d0e220"></a>Acknowledgements</h2>
</div>
<p>My thanks go to Kevlin Henney and Andrei Alexandrescu for
comments on this article.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e225" id=
"d0e225"></a>Bibiliography</h2>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Alexandrescu, Andrei, <span class=
"citetitle"><i class="citetitle">Modern C++ Design</i></span>,
2001, Addison-Wesley</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Czarnecki, K &amp; Eisenecker, UW,
<span class="citetitle"><i class="citetitle">Generative
Programming</i></span>, 2000, Addison-Wesley</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Coplien, JO, <span class=
"citetitle"><i class="citetitle">Multi-Paradigm Design for
C++</i></span>, 1999, Addison-Wesley</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
