/* boost random/detail/signed_unsigned_compare.hpp header file * * Copyright Jens Maurer 2000-2001 * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org for most recent version including documentation. * * Revision history */ #ifndef BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_COMPARE #define BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_COMPARE #include namespace boost { namespace random { /* * Correctly compare two numbers whose types possibly differ in signedness. * See boost::numeric_cast<> for the general idea. * Most "if" statements involve only compile-time constants, so the * optimizing compiler can do its job easily. * * With most compilers, the straightforward implementation produces a * bunch of (legitimate) warnings. Some template magic helps, though. */ namespace detail { template struct do_compare { }; template<> struct do_compare { // cast to the larger type is automatic with built-in types template static bool equal(T1 x, T2 y) { return x == y; } template static bool lessthan(T1 x, T2 y) { return x < y; } }; template<> struct do_compare : do_compare { }; template<> struct do_compare { template static bool equal(T1 x, T2 y) { return x >= 0 && static_cast(x) == y; } template static bool lessthan(T1 x, T2 y) { return x < 0 || static_cast(x) < y; } }; template<> struct do_compare { template static bool equal(T1 x, T2 y) { return y >= 0 && x == static_cast(y); } template static bool lessthan(T1 x, T2 y) { return y >= 0 && x < static_cast(y); } }; } // namespace detail template int equal_signed_unsigned(T1 x, T2 y) { typedef std::numeric_limits x_traits; typedef std::numeric_limits y_traits; return detail::do_compare::equal(x, y); } template int lessthan_signed_unsigned(T1 x, T2 y) { typedef std::numeric_limits x_traits; typedef std::numeric_limits y_traits; return detail::do_compare::lessthan(x, y); } } // namespace random } // namespace boost #endif // BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_COMPARE