Writing generic floating point code without a lot of template type constraints
Is there a way to indicate that the generic type T
can only be f32
or f64
? Otherwise, I introduce many restrictions templates such as: Copy
, Add<Output=T>
, Sub<Output=T>
, Mul
..., Div
... Zero
, One
etc., which gets a bit tedious after a while. Also, I am afraid that in the future this list will include Sin
, Cos
, Tan
and etc. In future.
source to share
You want num::traits::Float
available in a drawer num
.
Every type that satisfies the condition Float
is guaranteed Num + Copy + NumCast + PartialOrd + Neg<Output=Self>
. In turn, PartialEq + Zero + One + Add + Sub + Mul + Div + Rem
is required for num
. This is the answer to your first requests for basic arithmetic. Other operations, such as sin()
, cos()
are available as member functions in Float
.
Finally, f32
they f64
come out of the box as constructors Float
.
source to share