From 07ab79db64316806b51fff1e7f19828ffc5cee3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Lam?= Date: Wed, 29 Apr 2020 00:48:13 +0200 Subject: [PATCH] MathUtil: Fix Rectangle::GetWidth/Height for unsigned types `std::abs(x - y)` where x and y are unsigned integers fails to compile with an "call of overloaded 'abs(unsigned int)' is ambiguous" error on GCC, and even if it did compile, that expression still wouldn't give the correct result since `x - y` is unsigned. --- Source/Core/Common/MathUtil.h | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Source/Core/Common/MathUtil.h b/Source/Core/Common/MathUtil.h index 0e4b840524..c616b3d74d 100644 --- a/Source/Core/Common/MathUtil.h +++ b/Source/Core/Common/MathUtil.h @@ -6,6 +6,7 @@ #include #include +#include #include #include "Common/CommonTypes.h" @@ -71,8 +72,8 @@ struct Rectangle return left == r.left && top == r.top && right == r.right && bottom == r.bottom; } - T GetWidth() const { return std::abs(right - left); } - T GetHeight() const { return std::abs(bottom - top); } + constexpr T GetWidth() const { return GetDistance(left, right); } + constexpr T GetHeight() const { return GetDistance(top, bottom); } // If the rectangle is in a coordinate system with a lower-left origin, use // this Clamp. void ClampLL(T x1, T y1, T x2, T y2) @@ -92,6 +93,15 @@ struct Rectangle top = std::clamp(top, y1, y2); bottom = std::clamp(bottom, y1, y2); } + +private: + constexpr T GetDistance(T a, T b) const + { + if constexpr (std::is_unsigned()) + return b > a ? b - a : a - b; + else + return std::abs(b - a); + } }; template