haxe“应该是int"错误 [英] haxe "should be int" error
问题描述
假冒似乎认为某些东西必须是Int
.在以下功能中,
Haxe seems to assume that certain things must be Int
. In the following function,
class Main {
static function main() {
function mult_s<T,A>(s:T,x:A):A { return cast s*x; }
var bb = mult_s(1.1,2.2);
}
}
我得到了(使用Haxe 3.01):
I got (with Haxe 3.01):
Main.hx:xx: characters 48-49 : mult_s.T should be Int
Main.hx:xx: characters 50-51 : mult_s.A should be Int
任何人都可以解释为什么T
和A
应该是Int
而不是Float
吗?
Can anyone please explain why T
and A
should be Int
instead of Float
?
另一个令人困惑的例子是
A more puzzling example is this:
class Main {
public static function min<T:(Int,Float)>(t:T, t2:T):T { return t < t2 ? t : t2; }
static function main() {
var a = min(1.1,2.2); //compile error
var b = min(1,2); //ok
}
}
我不明白为什么t<t2
暗示t
或t2
是Int.但是Haxe似乎更喜欢Int
:如果使用Int
进行调用,则min
很好,但是如果使用Float
进行调用,则失败.这合理吗?
I can't see why t<t2
implies that either t
or t2
is Int. But Haxe seems prefer Int
: min
is fine if called with Int
's but fails if called with Float
's. Is this reasonable?
谢谢
推荐答案
min<T:(Int,Float)>
表示T
应该同时为 和Int
和 Float
.请参阅Haxe手册的约束部分. .
min<T:(Int,Float)>
means T
should be both Int
and Float
. See the constraints section of Haxe Manual.
鉴于Int
可以隐式转换为Float
,您可以安全地删除Int
的约束.即以下方法将起作用:
Given Int
can be converted to Float
implicitly, you can safely remove the constraint of Int
. i.e. the following will works:
class Test {
public static function min<T:Float>(t:T, t2:T):T { return t < t2 ? t : t2; }
static function main() {
var a = min(1.1,2.2); //ok
$type(a); //Float
trace(a); //1.1
var b = min(1,2); //ok
$type(b); //Int
trace(b); //1
}
}
这篇关于haxe“应该是int"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!