编译时(constexpr)float modulo?

Vin*_*ent 4 c++ algorithm floating-point modulo c++11

考虑以下函数,它在编译时根据参数类型计算积分或浮点模数:

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));
}
Run Code Online (Sandbox Code Playgroud)

这个功能的身体能改善吗?(我需要为整数和浮点类型都有一个函数).

Ker*_* SB 5

这是清理它的一种方法:

#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>());
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试在非算术类型上调用此函数,则会出现编译器错误.

  • 是`fmod``constexpr`? (2认同)