source: NonGTP/Boost/boost/random/detail/signed_unsigned_compare.hpp @ 857

Revision 857, 2.5 KB checked in by igarcia, 19 years ago (diff)
Line 
1/* boost random/detail/signed_unsigned_compare.hpp header file
2 *
3 * Copyright Jens Maurer 2000-2001
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE_1_0.txt or copy at
6 * http://www.boost.org/LICENSE_1_0.txt)
7 *
8 * See http://www.boost.org for most recent version including documentation.
9 *
10 * Revision history
11 */
12
13
14#ifndef BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_COMPARE
15#define BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_COMPARE
16
17#include <boost/limits.hpp>
18
19namespace boost {
20namespace random {
21
22/*
23 * Correctly compare two numbers whose types possibly differ in signedness.
24 * See boost::numeric_cast<> for the general idea.
25 * Most "if" statements involve only compile-time constants, so the
26 * optimizing compiler can do its job easily.
27 *
28 * With most compilers, the straightforward implementation produces a
29 * bunch of (legitimate) warnings.  Some template magic helps, though.
30 */
31
32namespace detail {
33template<bool signed1, bool signed2>
34struct do_compare
35{ };
36
37template<>
38struct do_compare<false, false>
39{
40  // cast to the larger type is automatic with built-in types
41  template<class T1, class T2>
42  static bool equal(T1 x, T2 y) { return x == y; }
43  template<class T1, class T2>
44  static bool lessthan(T1 x, T2 y) { return x < y; }
45};
46
47template<>
48struct do_compare<true, true> : do_compare<false, false>
49{ };
50
51template<>
52struct do_compare<true, false>
53{
54  template<class T1, class T2>
55  static bool equal(T1 x, T2 y) { return x >= 0 && static_cast<T2>(x) == y; }
56  template<class T1, class T2>
57  static bool lessthan(T1 x, T2 y) { return x < 0 || static_cast<T2>(x) < y; }
58};
59
60template<>
61struct do_compare<false, true>
62{
63  template<class T1, class T2>
64  static bool equal(T1 x, T2 y) { return y >= 0 && x == static_cast<T1>(y); }
65  template<class T1, class T2>
66  static bool lessthan(T1 x, T2 y) { return y >= 0 && x < static_cast<T1>(y); }
67};
68
69} // namespace detail
70
71
72template<class T1, class T2>
73int equal_signed_unsigned(T1 x, T2 y)
74{
75  typedef std::numeric_limits<T1> x_traits;
76  typedef std::numeric_limits<T2> y_traits;
77  return detail::do_compare<x_traits::is_signed, y_traits::is_signed>::equal(x, y);
78}
79
80template<class T1, class T2>
81int lessthan_signed_unsigned(T1 x, T2 y)
82{
83  typedef std::numeric_limits<T1> x_traits;
84  typedef std::numeric_limits<T2> y_traits;
85  return detail::do_compare<x_traits::is_signed, y_traits::is_signed>::lessthan(x, y);
86}
87
88} // namespace random
89} // namespace boost
90
91#endif // BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_COMPARE
Note: See TracBrowser for help on using the repository browser.