Я думаю, что следует выбрать наименьший тип, который будет содержать данное целое число:
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;
};
Тестовый код:
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;
}
Вывод: (c = char, s = short,я = int - из-за искажения имени)
c
s
i
Демонстрация: http://www.ideone.com/diALB
Примечание: конечно, я принимаю размер и диапазон типов, и даже несмотря на это, я мог бы выбрать неправильный диапазон;если это так, то, предоставляя правильный диапазон для шаблона класса within_range
, можно выбрать наименьший тип для данного целого числа.