I'm looking for a convenient idiom to check if a multiplication of two signed integers (longs or long longs) would overflow in versions of C++ where signed arithmetic overflow is undefined behavior (C or C++17 and earlier). I'm okay using any library functions available in C++17, but in an ideal world would like something cheaper than integer division (e.g., checking b <= std::numeric_limits<long long>::max() / a or b >= std::numeric_limits<long long>::lowest() / a or permutations with -b depending on the signedness of the arguments). In an ideal world the solution would be something the compiler could optimize away (so also not manually performing the multiplication one word at a time).
I'd like to avoid any idioms that first perform the multiplication, then sanity-check the result, because a compiler might remove the sanity check based on the assumption that signed arithmetic cannot overflow. (After all, overflow would be undefined behavior, so the compiler can assume the programmer would never let that happen.) Unfortunately, most algorithms I've seen suggested are of this form, so would appear to be unsafe.
See function
multiplication_would_overflow.