Created
November 16, 2022 10:32
-
-
Save CyberDNIWE/da55b40e972d8484c21c4d5de9f8851a to your computer and use it in GitHub Desktop.
poorly::midpoint, poor man's std::midpoint that avoids overflow caveat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Taken from Kevlin Henny video https://www.youtube.com/watch?v=YoaZzIZFErI | |
// poorly::midpoint is poor man's std::midpoint that avoids overflow caveat | |
namespace poorly | |
{ | |
struct autoswap_range {}; | |
template<typename T, typename T2 = T> | |
inline constexpr T midpoint(const T& low, const T2& high) noexcept | |
{ | |
return low + ((high - low) / 2); | |
} | |
template<typename T, typename T2 = T> | |
inline constexpr T midpoint(const T& low, const T2& high, const autoswap_range&) noexcept | |
{ | |
return poorly::midpoint((low < high ? low : high), (high < low ? low : high)); | |
} | |
}; | |
//Test it out! | |
constexpr int test() | |
{ | |
using namespace poorly; | |
// Simple cases | |
auto midpoint1 = midpoint(5, 10); // 7 | |
auto midpoint2 = midpoint(5, 11); // 8 | |
// Negatives, correct way around | |
auto midpoint3 = midpoint(-10, -5); //-8 | |
// Negatives, wrong way around | |
auto midpoint4 = midpoint(-5, -10); //-7 | |
auto midpoint5 = midpoint(-5, -10, {}); //-8 | |
// Equivalent | |
auto midpointAutoswap = midpoint(10, 5, {}); | |
auto midpointAutoswap2 = midpoint(10, 5, autoswap_range()); | |
} | |
int main() | |
{ | |
return test(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment