Sven Rosvall
Home - Contact Info
 Start
 Sven Rosvall
   CV
   Projects
   Articles
     Mixing Strings in C++
     C++ as a Safer C
       Listing 1
       Listing 2
       Listing 3
     C++ Lookup Mysteries
 Kari Rosvall
 The Rosvalls

Listing 1

// BoundedInt.h
// Bounds checked integers.
//

#ifndef BoundedInt_h
#define BoundedInt_h

#include <cassert>

#include "BoundedIntTraits.h"

template <int Lower, int Upper, 
          typename INT = typename BoundedIntTraits<Lower, Upper>::Type >
class BoundedInt
{
public:
  // Default constructor
  BoundedInt()
#ifndef NDEBUG
    : m_initialised(false)
#endif
    {}
  // Conversion constructor
  BoundedInt(int i)
    : m_i(i)
#ifndef NDEBUG
    , m_initialised(true)
#endif
    {
      // Check input value
      assert((Lower<=i) && (i<=Upper));
    }

  // Conversion back to a builtin type
  operator INT()
    {
      assert(m_initialised);
      return m_i;
    }

  // Assignment operators
  BoundedInt & operator+=(int rhs)
    {
      assert(m_initialised);

      // Check for overflow
      assert(m_i/2 + rhs/2 + (m_i&rhs&1) <= Upper/2);
      assert(Lower/2 <= m_i/2 + rhs/2 - ((m_i^rhs)&1));

      // Check result value
      assert((Lower<=m_i+rhs) && (m_i+rhs<=Upper));

      // Perform operation
      m_i += rhs;
      return *this;
    }
  // ...

  // Increment and decrement operators.
  BoundedInt & operator++()
    {
      assert(m_initialised);

      // Check for overflow
      assert(m_i < Upper);

      // Perform operation
      ++m_i;
      return *this;
    }
  // ...

private:
  INT m_i;
#ifndef NDEBUG
  bool m_initialised;
#endif
};

// Binary arithmetic operators
template <int Lower, int Upper, typename INT> 
inline BoundedInt<Lower, Upper, INT> 
operator+(BoundedInt<Lower, Upper, INT> lhs,
          BoundedInt<Lower, Upper, INT> rhs)
{
  return lhs.operator+=(rhs);
}
template <int Lower, int Upper, typename INT> 
inline BoundedInt<Lower, Upper, INT> 
operator+(BoundedInt<Lower, Upper, INT> lhs,
          int rhs)
{
  return lhs.operator+=(rhs);
}
template <int Lower, int Upper, typename INT> 
inline BoundedInt<Lower, Upper, INT> 
operator+(int lhs,
          BoundedInt<Lower, Upper, INT> rhs)
{
  return rhs.operator+=(lhs);
}
// ...

#endif


Copyright 2003-2012