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

基于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;
}

输出:

image

原文地址:https://www.cnblogs.com/quark/p/2700440.html