Using integer math alone, I\'d like to \"safely\" average two unsigned ints in C++.
What I mean by \"safely\" is avoiding overflows (and anything else that can be th
In C++20, you can use std::midpoint:
template
constexpr T midpoint(T a, T b) noexcept;
The paper P0811R3 that introduced std::midpoint recommended this snippet (slightly adopted to work with C++11):
#include
template
constexpr Integer midpoint(Integer a, Integer b) noexcept {
using U = std::make_unsigned::type;
return a>b ? a-(U(a)-b)/2 : a+(U(b)-a)/2;
}
For completeness, here is the unmodified C++20 implementation from the paper:
constexpr Integer midpoint(Integer a, Integer b) noexcept {
using U = make_unsigned_t;
return a>b ? a-(U(a)-b)/2 : a+(U(b)-a)/2;
}