Reputation: 20126
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
Reputation: 583
This is good: std::numeric_limits<T>::max()
or if you like boost: boost::integer_traits<T>::max()
.
Upvotes: 0
Reputation: 12552
Use std::numeric_limits<T>::max()
. Since C++11, this function is constexpr
and thus evaluated at compile-time.
Upvotes: 21