您的位置:首页 > 编程语言 > C语言/C++

利用C++模板特性计算各整数类型的最大最小值

2012-09-24 17:55 597 查看
基于C++模板编程,我们可以将一部分计算放到编译期来完成,还能够给编写代码带来很多方便。

比如题目中提到的,利用C++模板技术求各整数类型的最大最小值。

代码如下:

// indicates T is signed or unsigned
template< typename T > struct TFSigned
{
enum { fSigned = T(-1) < 0 };
};

// represents the bit length of T
template< typename T > struct TBitCount
{
enum { cBits = sizeof( T ) * 8 };
};

template< typename T, bool fSigned > struct TMinMaxHelper
{

};

template< typename T > struct TMinMaxHelper< T, true/*fSigned*/ >
{
static const T min = static_cast<T>( static_cast<T>(1) << ( TBitCount<T>::cBits - 1 ) );
static const T max = static_cast<T>( ~( static_cast<T>(1) << ( TBitCount<T>::cBits - 1 ) ) );
};

template< typename T > struct TMinMaxHelper< T, false/*fSigned*/ >
{
static const T min = static_cast<T>( 0 );
static const T max = static_cast<T>(-1);
};

template< typename T > struct TMinValue
{
static const T v = TMinMaxHelper< T, TFSigned<T>::fSigned >::min;
};

template< typename T > struct TMaxValue
{
static const T v = TMinMaxHelper< T, TFSigned<T>::fSigned >::max;
};


代码很容易看明白,使用以来也很简单:

int _tmain(int argc, _TCHAR* argv[])
{
printf("%d, %d\n", TMaxValue<short>::v, TMaxValue<int>::v);
printf("%d, %d\n", TMinValue<short>::v, TMinValue<int>::v);
getchar();
return 0;
}


输出:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐