ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
>[warning] 定义:泛型类型参数 如果它的包含类或者方法是泛型,则一个类型参数被认为是泛型。 >[warning] Definition: Generic Type Parameter A type parameter is said to be generic if its containing class or method is generic. 不可能构建一般的类型参数,例如 new T() 会有编译器错误。理由是Haxe只生成一个单独的函数,而且构造毫无意义。当类型参数为泛型的时候则不同:因为我们知道编译器会生成一个不同的函数对于每个类型参数组合,可以使用真实的类型替换 T new T()。 > It is not possible to construct normal type parameters, e.g. new T() is a compiler error. The reason for this is that Haxe generates only a single function and the construct makes no sense in that case. This is different when the type parameter is generic: Since we know that the compiler will generate a distinct function for each type parameter combination,it is possible to replace the T new T() with the real type. ~~~ typedef Constructible = { public function new(s:String):Void; } class Main { static public function main() { var s:String = make(); var t:haxe.Template = make(); } @:generic static function make<T:Constructible>():T { return new T("foo"); } } ~~~ 应该注意,这里使用从下到下的推断(第3.6.1节)来确定T的实际类型。这种类型的类型参数构建有两个需求才能工作:构建的类型参数必须是 > It should be noted that top-down inference (3.6.1) is used here to determine the actual type of T. There are two requirements for this kind of type parameter construction to work: The constructed type parameter must be * 是泛型,而且 * 显式约束(第3.2.1节)为有一个构造参数(第2.3.1节) > * generic and > * be explicitly constrained (3.2.1) to having a constructor (2.3.1). 这里,1,通过使用有 @generic 元数据,2. 通过 T 被约束为可构造的。这个约束适用于String 和haxe.Template 因为它们都有一个构造函数,接受一个单一的Sting参数。果然,相关的JavaScript输出看起来和预期的一样: > Here, 1. is given by make having the @:generic metadata, and 2. by T being constrained to Constructible. The constraint holds for both String and haxe.Template as both have a constructor accepting a singular String argument. Sure enough, the relevant JavaScript output looks as expected: ~~~ var Main = function() { } Main.__name__ = true; Main.make_haxe_Template = function() { return new haxe.Template("foo"); } Main.make_String = function() { return new String("foo"); } Main.main = function() { var s = Main.make_String(); 11 var t = Main.make_haxe_Template(); } ~~~