I think he should choose the smallest type that would hold the given integer:
class true_type {}; class false_type {}; template<bool> struct bool2type { typedef true_type type; }; template<> struct bool2type<false> { typedef false_type type; }; template<int M, int L, int H> struct within_range { static const bool value = L <= M && M <=H; typedef typename bool2type<value>::type type; }; template<int M, class booltype> struct IntegerType; template<int Max> struct IntegerType<Max,typename within_range<Max, 0, 127>::type > { typedef char type; }; template<int Max> struct IntegerType<Max,typename within_range<Max, 128, 32767>::type > { typedef short type; }; template<int Max> struct IntegerType<Max,typename within_range<Max, 32768, INT_MAX>::type > { typedef int type; }; template <int Max> struct Integer { typedef typename IntegerType<Max, true_type>::type type; };
Test code:
int main() { cout << typeid(Integer<122>::type).name() << endl; cout << typeid(Integer<1798>::type).name() << endl; cout << typeid(Integer<890908>::type).name() << endl; return 0; }
Output: (c = char, s = short, i = int - due to name change)
c s i
Demo: http://www.ideone.com/diALB
Note: of course, I assume the size and range of types, and even so, I might choose the wrong range; if so, then by providing the correct range to the within_range class within_range , you can select the smallest type for the given integer.
Nawaz Aug 12 2018-11-11T00: 00Z
source share