Due to implicit conversion and the fact that std::numeric_limits<T>::max() and friends return type T, it seems non-trivial to write a function bool cmp(IntA a, IntB b) that "does the right thing" to conceptually return a < b;. That is, if they share a common range, compare, if not, determine if a is less than b regardless of number of bits or signedness. Is there a simpler implementation than this naive one?:
template <typename IntA, typename IntB>
[[nodiscard]] constexpr bool cmp(IntA a, IntB b) noexcept {
static_assert(std::is_integral_v<IntA>);
static_assert(sizeof(IntA) <= sizeof(long long int), "We assume we can fit everything into long long");
static_assert(std::is_integral_v<IntB>);
static_assert(sizeof(IntB) <= sizeof(long long int), "We assume we can fit everything into long long");
if (a < 0) {
if (b < 0) {
return static_cast<signed long long int>(a) < static_cast<signed long long int>(b);
} else {
return true;
}
} else {
if (b < 0) {
return false;
} else {
return static_cast<unsigned long long int>(a) < static_cast<unsigned long long int>(b);
}
}
}
https://godbolt.org/z/aPbozGW9j
And what can we do to ensure it gets fully optimized?