
Zachary Turner wrote:
I am often frustrated by the inability of std::min and std::max to deal with data types of different ranges. For example:
boost::uint64_t big = 9876543210ULL; boost::uint32_t small = 12345;
boost::uint32_t smallest = std::min(big, small);
will generate a compiler warning about possible loss of data due to converting from boost::uint64_t to boost::uint32_t.
It doesn't seem to compile: http://codepad.org/IiFba8MF I guess you mean: boost::uint32_t smallest = std::min<boost::uint32_t>(big, small);
Previously there was a discussion on the list about adding operators such as is_addable, is_multipliable, is_less_comparable, etc. Using such a class, one could re-write min and max as follows (...):
namespace boost {
template<class A, class B> struct min_result { typedef mpl::if_c<(integer_traits<A>::const_max < integer_traits<B>::const_max), A, B>::type type; };
template<class A, class B> struct max_result { typedef mpl::if_c<(integer_traits<A>::const_min > integer_traits<B>::const_min), A, B>::type type; };
template<class A, class B> min_result<A,B>::type min(const A& a, const B& b) { return static_cast<min_result<A,B>::type>((a < b) ? a : b); }
template<class A, class B> max_result<A,B>::type max(const A& a, const B& b) { return static_cast<max_result<A,B>::type>((a > b) ? a : b); }
Excuse me, where do you use is_addable, is_multipliable, is_less_comparable?
I'm sure there's some implementation details I haven't considered, but is there any fundamental reason why an approach like this would be flawed or undesirable?
I think your suggestion is quite reasonable, but I see two drawbacks: * It only seems to support numeric types. Why not support the minimum of two datetime objects, or the minimun of two std::string objects? * It returns by-value. In general, I prefer min/max to return a reference to the object itself, instead of a copy. Like std::min and std::max (C++03). Both drawbacks could be avoided by renaming your function, for example to numeric_min_value. HTH, Niels -- Niels Dekker http://www.xs4all.nl/~nd/dekkerware Scientific programmer at LKEB, Leiden University Medical Center