指定された整数を保持する最小の型を選択する必要があると思います:
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、i=int - 名前マングリングのため)
c
s
i
デモ : http://www.ideone.com/diALB
注: もちろん、型のサイズと範囲を想定していますが、それにもかかわらず、間違った範囲を選択した可能性があります。その場合、within_range
クラス テンプレートに正しい範囲を指定すると、指定された整数の最小の型を選択できます。