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 2

// BoundedIntTraits.h
// Information on types based on a given value range.
//

#ifndef BoundedIntTraits_h
#define BoundedIntTraits_h

#include <climits>

// Compile time assertion:
template <bool condition>
struct StaticAssert;
template <>
struct StaticAssert<true> {};

#ifndef NO_PARTIAL_SPECIALIZATIONS

// Template for finding the smallest built-in type that can
// hold a given value range, based on a set of conditions.
template <bool sign, bool negbyte, bool negshort, bool negint,
          bool sbyte, bool ubyte, bool sshort, bool ushort, bool sint>
struct BoundedIntType;

template <>
struct BoundedIntType<true, true, true, true,
                      true, true, true, true, true>
{ typedef signed char Type; };

template <bool negbyte, bool sbyte, bool ubyte>
struct BoundedIntType<true, negbyte, true, true,
                      sbyte, ubyte, true, true, true>
{ typedef signed short Type; };

template <bool negbyte, bool negshort,
          bool sbyte, bool ubyte, bool sshort, bool ushort>
struct BoundedIntType<true, negbyte, negshort, true,
                      sbyte, ubyte, sshort, ushort, true>
{ typedef signed int Type; };

template <bool sbyte>
struct BoundedIntType<false, true, true, true,
                      sbyte, true, true, true, true>
{ typedef unsigned char Type; };

template <bool sbyte, bool ubyte, bool sshort>
struct BoundedIntType<false, true, true, true,
                      sbyte, ubyte, sshort, true, true>
{ typedef unsigned short Type; };

template <bool sbyte, bool ubyte, bool sshort, bool ushort, bool sint>
struct BoundedIntType<false, true, true, true,
                      sbyte, ubyte, sshort, ushort, sint>
{ typedef unsigned int Type; };
#endif

//
// The traits template provides value range information to
// the BoundedIntType to get the smallest possible type.
//
template <int Lower, int Upper>
struct BoundedIntTraits
{
  StaticAssert<(Lower <= Upper)> check;
#ifdef NO_PARTIAL_SPECIALIZATIONS
  typedef int Type;
#else
  typedef typename
    BoundedIntType<Lower < 0,
                   Lower >= CHAR_MIN,
                   Lower >= SHRT_MIN,
                   Lower >= INT_MIN,
                   Upper <= CHAR_MAX,
                   Upper <= UCHAR_MAX,
                   Upper <= SHRT_MAX,
                   Upper <= USHRT_MAX,
                   Upper <= INT_MAX >::Type Type;
#endif
};


Copyright 2003-2012