63 if constexpr (std::is_signed_v<T> &&
sizeof(T) >=
sizeof(
int)) {
64 if (((summand_2 >= 0) && (summand_1 > std::numeric_limits<T>::max() - summand_2)) ||
65 ((summand_2 < 0) && (summand_1 < std::numeric_limits<T>::min() - summand_2)))
67 result = summand_1 + summand_2;
69 }
else if constexpr (std::is_signed_v<T> &&
sizeof(T) <
sizeof(
int)) {
70 const int res = summand_1 + summand_2;
71 if ((res > std::numeric_limits<T>::max()) || (res < std::numeric_limits<T>::min())) {
74 result =
static_cast<T
>(res);
77 result = summand_1 + summand_2;
78 return result < summand_1;
100#if defined(__GNUC__) || defined(__clang__)
101#if __GNUC__ >= 5 || __clang_major__ >= 3
113#define SPECIALIZE_builtin_add_overflow(type, builtin_name) \
117 constexpr bool builtin_add_overflow<type>(type summand_1, type summand_2, type & result) { \
118 return builtin_name(summand_1, summand_2, &result); \
121SPECIALIZE_builtin_add_overflow(
int, __builtin_sadd_overflow);
122SPECIALIZE_builtin_add_overflow(
long, __builtin_saddl_overflow);
123SPECIALIZE_builtin_add_overflow(
long long, __builtin_saddll_overflow);
125SPECIALIZE_builtin_add_overflow(
unsigned int, __builtin_uadd_overflow);
126SPECIALIZE_builtin_add_overflow(
unsigned long, __builtin_uaddl_overflow);
127SPECIALIZE_builtin_add_overflow(
unsigned long long, __builtin_uaddll_overflow);
129#undef SPECIALIZE_builtin_add_overflow
157T
add(T summand_1, T summand_2) {
160 throw std::overflow_error(
"Overflow in addition");
189 if constexpr (std::is_signed_v<T>) {
190 if (num == std::numeric_limits<T>::min())
191 return std::numeric_limits<T>::max();
192 return num < 0 ? -num : num;
bool builtin_add_overflow(T summand_1, T summand_2, T &result)
Overflow addition check using compiler intrinsics.
Definition safe_op.hpp:96
bool fallback_add_overflow(T summand_1, T summand_2, T &result)
Check the addition of two numbers for overflows for signed integer types larger than int or with the ...
Definition safe_op.hpp:62
Arithmetic operations with overflow checks.
Definition safe_op.hpp:17
T add(T summand_1, T summand_2)
Safe addition, throws an exception on overflow.
Definition safe_op.hpp:157
T abs(T num) noexcept
Calculates the absolute value of a number without producing negative values.
Definition safe_op.hpp:188