zoukankan      html  css  js  c++  java
  • 利用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

  • 相关阅读:
    B1028人口普查
    B1004成绩排名
    B1041考试座位号
    A1009 Product of Polynomials多项式相乘
    A1002 A+B for Polynomials 多项式相加
    B1010一元多项式求导
    A1065 A+Band C(64 bit)
    A1046 Shortest Distance 最短路径
    排序
    windows 平台使用wireshark命令行抓包
  • 原文地址:https://www.cnblogs.com/quark/p/2700440.html
Copyright © 2011-2022 走看看