编译时(constexpr)浮点取模? [英] Compile-time (constexpr) float modulo?

查看:70
本文介绍了编译时(constexpr)浮点取模?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

推荐答案

这是清理此问题的一种方法:

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.

这篇关于编译时(constexpr)浮点取模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆