Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time (constexpr) float modulo?

Consider the following function that computes the integral or floating-point modulo depending on the argument type, at compile-time:

template<typename T>
constexpr T modulo(const T x, const T y)
{
    return (std::is_floating_point<T>::value) ? (x < T() ? T(-1) : T(1))*((x < T() ? -x : x)-static_cast<long long int>((x/y < T() ? -x/y : x/y))*(y < T() ? -y : y))
    : (static_cast<typename std::conditional<std::is_floating_point<T>::value, int, T>::type>(x)
      %static_cast<typename std::conditional<std::is_floating_point<T>::value, int, T>::type>(y));
}

Can the body of this function be improved ? (I need to have a single function for both integer and floating-point types).

like image 880
Vincent Avatar asked Jan 12 '13 15:01

Vincent


1 Answers

Here's one way to clean this up:

#include <type_traits>
#include <cmath>

template <typename T>  //     integral?       floating point?
bool remainder_impl(T a, T b, std::true_type, std::false_type) constexpr
{
    return a % b;  // or whatever
}

template <typename T>  //     integral?        floating point?
bool remainder_impl(T a, T b, std::false_type, std::true_type) constexpr
{
    return std::fmod(a, b); // or substitute your own expression
}

template <typename T>
bool remainder(T a, T b) constexpr
{
    return remainder_impl<T>(a, b,
             std::is_integral<T>(), std::is_floating_point<T>());
}

If you try and call this function on a type that's not arithmetic, you'll get a compiler error.

like image 63
Kerrek SB Avatar answered Sep 21 '22 20:09

Kerrek SB