bool isUnit(Vec)(in Vec v, float tolerance = kindaSmallNumber){
import std.math: abs;
import std.conv: to;
auto length = v.lengthSquared;
return abs(to!(typeof(length))(1) - length) < tolerance;
}
Here I just want to calculate 1 - length
but length could be of type double or float. I don't want to convert 1 from integer to float
or double
at runtime.
Do I have to do to!(typeof(length))(1) - length
or can I just do 1 - length
and 1
will always be of the same type as length?
The type of 1 is irrelevant there. It will be automatically converted to an appropriate type for arithmetic with length.
From http://dlang.org/spec/expression.html#AddExpression
If either operand is a floating point type, the other is implicitly converted to floating point and they are brought to a common type via the usual arithmetic conversions.
So it is done automatically anyway by the compiler (which btw is known at compile time, of course, so it doesn't do any runtime stuff here).
But for other people who want to know the answer to the specific question, you could use typed literals like 1.0
or a type constructor, like typeof(length)(1)
.