zenpoy
zenpoy

Reputation: 20126

How to find the max value of unknown integer type

How can I find the maximal integer value of an unknown type? Is there something more efficient than this:

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

Upvotes: 5

Views: 1154

Answers (3)

soerium
soerium

Reputation: 583

This is good: std::numeric_limits<T>::max() or if you like boost: boost::integer_traits<T>::max().

Upvotes: 0

mavam
mavam

Reputation: 12552

Use std::numeric_limits<T>::max(). Since C++11, this function is constexpr and thus evaluated at compile-time.

Upvotes: 21

Bathsheba
Bathsheba

Reputation: 234685

std::numeric_limits<T>::max() is a good starting point.

Upvotes: 5

Related Questions