point: make distance metrics constexpr

This commit is contained in:
Danny Robson 2015-09-15 21:06:43 +10:00
parent 95e5fc5834
commit 21b51a5011
2 changed files with 13 additions and 9 deletions

View File

@ -45,16 +45,16 @@ namespace util {
// distance operators
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type distance (point<S,T>, point<S,U>);
constexpr typename std::common_type<T,U>::type distance (point<S,T>, point<S,U>);
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type distance2 (point<S,T>, point<S,U>);
constexpr typename std::common_type<T,U>::type distance2 (point<S,T>, point<S,U>);
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type manhattan (point<S,T>, point<S,U>);
constexpr typename std::common_type<T,U>::type manhattan (point<S,T>, point<S,U>);
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type chebyshev (point<S,T>, point<S,U>);
constexpr typename std::common_type<T,U>::type chebyshev (point<S,T>, point<S,U>);
// iostream operators
template <size_t S, typename T>

View File

@ -48,16 +48,20 @@ namespace util {
//-------------------------------------------------------------------------
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type
constexpr typename std::common_type<T,U>::type
distance (point<S,T> a, point<S,U> b)
{
using type_t = typename std::common_type<T,U>::type;
static_assert (std::is_floating_point<type_t>::value,
"sqrt likely requires fractional types");
return std::sqrt (distance2 (a, b));
}
//-------------------------------------------------------------------------
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type
constexpr typename std::common_type<T,U>::type
distance2 (point<S,T> a, point<S,U> b)
{
typename std::common_type<T,U>::type sum {0};
@ -71,13 +75,13 @@ namespace util {
//-------------------------------------------------------------------------
template <size_t S, typename T, typename U>
typename std::common_type<T,U>::type
constexpr typename std::common_type<T,U>::type
manhattan (point<S,T> a, point<S,U> b)
{
typename std::common_type<T,U>::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 <size_t S, typename T, typename U>
typename std::common_type<T,U>::type
constexpr typename std::common_type<T,U>::type
chebyshev(point<S,T> a, point<S,U> b)
{
return util::max (abs (a - b));