C++中检测整数类型的最大、最小值

由于time_t底层类型根据编译器不同其最大值是不同的,由于程序中用到其最大值,故而想手某种手段检测其极值,下面是使用模板函数检测的代码。

当然也可以定义为宏,或者将其定义为常量。如果定义为常量就不能检测用户自定义类型的最大最小值,使用宏或者模板支持用户自定义类型。

遗憾的是在C++98中还没有办法自动获取变量的类型,等C++0X一发布,这个函数就可以用一个变量作为参数,然后就可以获得某个变量可能的最大值与最小值, 会使这两个函数模板更有用。

#include
#include
using namespace std;

template
inline T MaxOf(void)
{
        return T((T(-1) > 0 ? T(-1) : (~(T(1)<<((sizeof(T)<<3) - 1)))));
}

template
inline T MinOf(void)
{
        return T((T(-1) > 0 ? 0 : (T(1)<<( (sizeof(T)<<3) - 1))));
}

int main(void)
{

        cout<<"MaxOf( time_t) = "<< MaxOf< time_t>()<<", MinOf( time_t) = "<<  MinOf< time_t>() <         cout<<"MaxOf( char) = "<< (int) MaxOf< char>()<<", MinOf( char) = "<< (int) MinOf< char>() <         cout<<"MaxOf(unsigned char) = "<< (int) MaxOf ()<<", MinOf(unsigned char) = "<< (int) MinOf () <         cout<<"MaxOf(short) = "< ()<<", MinOf(short) = "< ()<         cout<<"MaxOf(unsigned short) = "< ()<<", MinOf(unsigned short) = "< ()<         cout<<"MaxOf(int) = "< ()<<", MinOf(int) = "< ()<         cout<<"MaxOf(unsigned int) = "< ()<<", MinOf(unsigned int) = "< ()<         cout<<"MaxOf(long) = "< ()<<", MinOf(long) = "< ()<         cout<<"MaxOf(unsigned long) = "< ()<<", MinOf(unsigned long) = "< ()<         cout<<"MaxOf(long long) = "< ()<<", MinOf(long long) = "< ()<         cout<<"MaxOf(unsigned long long) = "< ()<<", MinOf(unsigned long long) = "< ()<         return 0;
}

你可能感兴趣的:(C++,c,编译器)