5

如何找到未知类型的最大整数值?有没有比这更有效的东西:

template<class T>
T test(T i) {
    if (((T)-1) > 0)
       return -1;
    T max_neg = ~(1 << ((sizeof(T)*8)-1));
    T all_ones = -1;
    T max_pos = all_ones & max_neg;
    return max_pos;
}
4

3 回答 3

21

使用std::numeric_limits<T>::max(). 从 C++11 开始,此函数constexpr在编译时进行评估。

于 2013-07-08T08:19:45.800 回答
5

std::numeric_limits<T>::max()是一个很好的起点。

于 2013-07-08T08:19:44.327 回答
0

这很好:std::numeric_limits<T>::max()或者如果你喜欢 boost: boost::integer_traits<T>::max()

于 2013-07-08T08:28:08.730 回答