FR: add static assert to degreesToRadians() and radiansToDegrees() to check if FloatType is indeed a floating point type

This is just a small nicety to protect me from myself:

Because of the small values, passing integers to degreesToRadians() or radiansToDegrees() does not make much sense - but it’s an easy mistake to make. just write AffineTransform::rotation(degreesToRadians(180)) and you’re screwed. This can easily be addresses by adding static asserts to those functions:

static_assert(!std::is_integral<FloatType>::value, "angles cannot be integers.")

One could also use std::is_floating_point() but then the assert also fires in case someone comes along with his custom fixed point type.

PS.: It’s really nice to have those functions. The gems never stop surfacing!

best,
Ben

Edit: changed “is_integer” to “is_integral”. There’s no std::is_integer.

This seems like a PR would get it into the library way faster than voting for it, no?

I wonder, if degreesToRadians(180) really compiles?

/** Converts an angle in degrees to radians. */
template <typename FloatType>
JUCE_CONSTEXPR FloatType degreesToRadians (FloatType degrees) noexcept     { return degrees * (MathConstants<FloatType>::pi / FloatType (180)); }

If FloatType is int, the compiler should choke, since MathConstants<int>::pi is not defined afaik.

But I could be wrong, haven’t tested it

Sorry, just seen this:

template <typename FloatType>
const FloatType MathConstants<FloatType>::pi = static_cast<FloatType> (3.141592653589793238L);

So yes, pi is available implicitly casted to anything…

I guess it would make sense to add the static assert to MathConstants instead. Who would want the integer version of pi?

You mean actually doing something about it instead of whining and complaining :slight_smile:

Here’s the pull-request: https://github.com/WeAreROLI/JUCE/pull/569

2 Likes

An alternative I chose is to check, if the computation was not degraded:

/** Converts an angle in degrees to radians. */
template <typename FloatType>
constexpr FloatType degreesToRadians (FloatType degrees) noexcept
{
    constexpr auto factor = (MathConstants<FloatType>::pi / FloatType (180));
    static_assert (factor != FloatType (0), "Conversion is degraded for this type");
    return degrees * factor;
}