我认为应该选择能容纳给定整数的最小类型:
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=字符,s=短整型,i=整型-由于名称重整)
c
s
i
示例代码:http://www.ideone.com/diALB
注意:当然,我假设类型的大小和范围,即使如此,我可能选择了错误的范围。如果是这样,那么提供正确的范围给 within_range
类模板,就可以为给定的整数选择最小的类型。
dataItem
不应超过10000
吗? - iammilindInteger<10000>::type
应该解析为uint16_t
,因为你不能将10000存储在uint8_t
中,但可以将其存储在uint16_t
中。 - In silicouint8_t
或uint16_t
等呢?例如,如果你发现需要写出的值是10000
,那么解析器将会计算出还需要写出uint16_t
。 - In silico