Sign in to follow this  
samgzman

generic programming troubles with numeric_limits

Recommended Posts

I'm implementing a generic algorithm which needs to determine the "largest negative" and "largest positive" representable values for a given type. For an integral type, these would simply be numeric_limits<integral_type>::min() and numeric_limits<integral_type>::max() respectively. However, for floating-point types, numeric_limits<floating_point_type>::min() returns the smallest positive representable quantity which is not what I want. For floating point types, the values I need are -numeric_limits<floating_point_type>::max() and numeric_limits<floating_point_type>::max(). Is there an existing solution to this problem available that I am missing, or is the best solution to implment my own traits type?

Share this post


Link to post
Share on other sites
IEEE 754, CRAY, IBM S/390 and VAX floating point have a sign bit, making the maximum positive and negative magnitudes equal. http://owen.sj.ca.us/~rk/howto/fltpt/index.html

So that should cover the vast majority of platforms you'd likely be aiming at.
http://stackoverflow.com/questions/2234468/do-any-real-world-cpus-not-use-ieee-754

Share this post


Link to post
Share on other sites
May-be something like this would help:


#include <iostream>
#include <limits>
#include <boost/utility/enable_if.hpp>

template <class T>
typename boost::enable_if_c<std::numeric_limits<T>::is_integer, T>::type min_value()
{
return std::numeric_limits<T>::min();
}

template <class T>
typename boost::disable_if_c<std::numeric_limits<T>::is_integer, T>::type min_value()
{
return -std::numeric_limits<T>::max();
}

int main()
{
std::cout << min_value<short>() << ' ' << min_value<double>() << '\n';
}



(enable_if_c and disable_if_c should be easy to implement yourself if you don't want boost)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this