2

Possible Duplicate:
Best way to detect integer overflow in C/C++

Currently I use the following function:

template<typename T, typename U>
bool is_mul_safe(T x, U y) {
    return (ld(x * 1.) + ld(y * 1.)) - (sizeof(decltype(x * y)) << 3) <= 0;
}

Is there a standard library function which provides the same functionality?

Community
  • 1
  • 1
0xbadf00d
  • 17,405
  • 15
  • 67
  • 107
  • Btw. I would like to know if there's any type_trait I could replace the decltype with. – 0xbadf00d Jun 16 '11 at 10:06
  • 2
    I'd simply perform the multiplication and use a subsequent division to check if there was an overflow. Thtis will be certainly faster than calling `ld()` twice. – Sven Marnach Jun 16 '11 at 10:09
  • Pardon my ignorance, what's `ld`? Is that standard C? – Kerrek SB Jun 16 '11 at 11:25
  • Are T and U unsigned integer types? – TonyK Jun 16 '11 at 13:16
  • ld (logarithm dualis) is basically a `static inline` helper function which returns `::log(x) / ::log(2)`. Just for convenience. T and U should be numeric types. – 0xbadf00d Jun 16 '11 at 19:18
  • "numeric types"? That includes floating-point types! How on earth is your `sizeof(decltype)` going to work for floating-point types? Get a grip, FrEEzE2046. – TonyK Jun 16 '11 at 20:24
  • I'm sorry, what I mean is "integral types". However, this could be done ensured with enable_if. – 0xbadf00d Jun 17 '11 at 07:33

0 Answers0