通用数字文字
Generic number literals
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;
}
这里我只想计算1 - length
,但是length可以是double或者float类型。我不想在运行时将 1 从整数转换为 float
或 double
。
我必须做 to!(typeof(length))(1) - length
还是我可以只做 1 - length
并且 1
总是与长度相同的类型?
1 的类型与此处无关。它会自动转换为适合长度算术的类型。
来自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.
所以它无论如何都是由编译器自动完成的(顺便说一句,当然,编译器在编译时是已知的,所以它不会在这里做任何运行时的事情)。
但对于其他想知道特定问题答案的人,您可以使用 1.0
之类的类型文字或 typeof(length)(1)
.
之类的类型构造函数
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;
}
这里我只想计算1 - length
,但是length可以是double或者float类型。我不想在运行时将 1 从整数转换为 float
或 double
。
我必须做 to!(typeof(length))(1) - length
还是我可以只做 1 - length
并且 1
总是与长度相同的类型?
1 的类型与此处无关。它会自动转换为适合长度算术的类型。
来自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.
所以它无论如何都是由编译器自动完成的(顺便说一句,当然,编译器在编译时是已知的,所以它不会在这里做任何运行时的事情)。
但对于其他想知道特定问题答案的人,您可以使用 1.0
之类的类型文字或 typeof(length)(1)
.