...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Safe Numerics |
// compare any pair of integers template<class T, class U> bool constexpr safe_compare::less_than(const T & lhs, const U & rhs); template<class T, class U> bool constexpr safe_compare::greater_than(const T & lhs, const U & rhs); template<class T, class U> bool constexpr safe_compare::less_than_equal(const T & lhs, const U & rhs); template<class T, class U> bool constexpr safe_compare::greater_than_equal(const T & lhs, const U & rhs); template<class T, class U> bool constexpr safe_compare::equal(const T & lhs, const U & rhs); template<class T, class U> bool constexpr safe_compare::not_equal(const T & lhs, const U & rhs);
Compare two primitive integers. These functions will return a
correct result regardless of the type of the operands. Specifically it is
guaranteed to return the correct arithmetic result when comparing signed
and unsigned types of any size. It does not follow the standard C/C++
procedure of converting the operands to some common type then doing the
compare. So it is not equivalent to the C/C++ binary operations
<
, >
,
,
>
=<=
, ==
, !=
and shouldn't be used
by user programs which should be portable to standard C/C++ integer
arithmetic. The functions are free functions defined inside the namespace
boost::numeric::safe_compare
.
All template parameters of the functions must be C/C++ built-in
integer types,
,
char
....int
#include <cassert> #include <safe_compare.hpp> using namespace boost::numeric; const short int x = -64; const unsigned int y = 42000; assert(x < y); // fails assert(safe_compare::less_than(x, y)); // OK