Occasionally I find that I need to compare `signed`

and `unsigned int`

values. This understandably throws warnings. So I wrote the following helpful functions to safely compare the values when needed. Obviously I try not to, but there’s times when I’m forced to.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
template<typename T1, typename T2> typename std::enable_if<std::is_same<T1,signed int>::value,bool>::type SignedUnsignedEquality(T1 i, T2 u) { if(i < 0) return false; return u == static_cast<unsigned int>(i); } template<typename T1, typename T2> typename std::enable_if<std::is_same<T1,unsigned int>::value,bool>::type SignedUnsignedEquality(T1 u, T2 i) { return SignedUnsignedEquality(i,u); } template<typename T1, typename T2> typename std::enable_if<std::is_same<T1,signed int>::value,bool>::type SignedUnsignedLessThan(T1 i, T2 u) { if(i < 0) return true; return static_cast<unsigned int>(i) < u; } template<typename T1, typename T2> typename std::enable_if<std::is_same<T1,unsigned int>::value,bool>::type SignedUnsignedLessThan(T1 u, T2 i) { if(i < 0) return false; return u < static_cast<unsigned int>(i); } template<typename T1, typename T2> typename std::enable_if<std::is_same<T1,signed int>::value,bool>::type SignedUnsignedGreaterThan(T1 i, T2 u) { if(i < 0) return false; return static_cast<unsigned int>(i) > u; } template<typename T1, typename T2> typename std::enable_if<std::is_same<T1,unsigned int>::value,bool>::type SignedUnsignedGreaterThan(T1 u, T2 i) { if(i < 0) return true; return u > static_cast<unsigned int>(i); } template<typename T1, typename T2> bool SignedUnsignedLessThanEqual(T1 p1, T2 p2) { return SignedUnsignedEquality(p1,p2) || SignedUnsignedLessThan(p1,p2); } template<typename T1, typename T2> bool SignedUnsignedGreaterThanEqual(T1 p1, T2 p2) { return SignedUnsignedEquality(p1,p2) || SignedUnsignedGreaterThan(p1,p2); } |

It allows me to compare `signed int`

and `unsigned int`

values as either the left or right parameters.