From 21b51a501121881c037a36ceaa2da9ac944f994d Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Tue, 15 Sep 2015 21:06:43 +1000 Subject: [PATCH] point: make distance metrics constexpr --- point.hpp | 8 ++++---- point.ipp | 14 +++++++++----- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/point.hpp b/point.hpp index 22b0964d..5faf9df0 100644 --- a/point.hpp +++ b/point.hpp @@ -45,16 +45,16 @@ namespace util { // distance operators template - typename std::common_type::type distance (point, point); + constexpr typename std::common_type::type distance (point, point); template - typename std::common_type::type distance2 (point, point); + constexpr typename std::common_type::type distance2 (point, point); template - typename std::common_type::type manhattan (point, point); + constexpr typename std::common_type::type manhattan (point, point); template - typename std::common_type::type chebyshev (point, point); + constexpr typename std::common_type::type chebyshev (point, point); // iostream operators template diff --git a/point.ipp b/point.ipp index e2dd343a..6bf7aa44 100644 --- a/point.ipp +++ b/point.ipp @@ -48,16 +48,20 @@ namespace util { //------------------------------------------------------------------------- template - typename std::common_type::type + constexpr typename std::common_type::type distance (point a, point b) { + using type_t = typename std::common_type::type; + static_assert (std::is_floating_point::value, + "sqrt likely requires fractional types"); + return std::sqrt (distance2 (a, b)); } //------------------------------------------------------------------------- template - typename std::common_type::type + constexpr typename std::common_type::type distance2 (point a, point b) { typename std::common_type::type sum {0}; @@ -71,13 +75,13 @@ namespace util { //------------------------------------------------------------------------- template - typename std::common_type::type + constexpr typename std::common_type::type manhattan (point a, point b) { typename std::common_type::type sum {0}; for (size_t i = 0; i < S; ++i) - sum += std::abs (a.data[i] - b.data[i]); + sum += util::abs (a.data[i] - b.data[i]); return sum; } @@ -85,7 +89,7 @@ namespace util { //------------------------------------------------------------------------- template - typename std::common_type::type + constexpr typename std::common_type::type chebyshev(point a, point b) { return util::max (abs (a - b));