编译时(constexpr)浮点取模?

编程入门 行业动态 更新时间:2024-10-26 22:20:06
本文介绍了编译时(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)浮点取模?

本文发布于:2023-10-24 08:59:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   constexpr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!