Macros 如何制作参数化枚举生成宏?
我想用宏构建一个枚举,包括定义它的类型参数 有两个源代码描述使用添加枚举字段,但我没有找到任何源代码描述如何使用宏使用指定参数类型构建枚举。有一个文档条目,用于说明有关参数类型的宏的限制,但该条目仍然为空 其思想是使用宏生成指定数量的任一枚举,并增加参数类型的数量Macros 如何制作参数化枚举生成宏?,macros,haxe,Macros,Haxe,我想用宏构建一个枚举,包括定义它的类型参数 有两个源代码描述使用添加枚举字段,但我没有找到任何源代码描述如何使用宏使用指定参数类型构建枚举。有一个文档条目,用于说明有关参数类型的宏的限制,但该条目仍然为空 其思想是使用宏生成指定数量的任一枚举,并增加参数类型的数量 //Either.hx @:build(macros.build.EitherBuildMacro.build(10)) // enum Either {} <- this isnt sufficient as we need
//Either.hx
@:build(macros.build.EitherBuildMacro.build(10))
// enum Either {} <- this isnt sufficient as we need to generated several
// enums (in this example 10 of them) with parameter types...
//And it should generate
enum Either2<A,B>{
_1(value:A);
_2(value:B);
}
enum Either3<A,B,C>{
_1(value:A);
_2(value:B);
_3(value:C);
}
enum Either4<A,B,C,D>{
_1(value:A);
_2(value:B);
_3(value:C);
_4(value:D);
}
//etc until enum Either10<A,B,C,D,E,F,G,H,I,J>
///eather.hx
@:build(macros.build.EitherBuildMacro.build(10))
//枚举{}@:build()
确实不是正确的方法,因为它只构建一个特定类型。相反,您可以结合使用:
使用-D dump=pretty
可以看到,这会生成2
-10
:
例如,Either2.dump
如下所示:
@:used
enum Either2<A : Either2.A,B : Either2.B> {
_1(value:Either2.A);
_2(value:Either2.B);
}
@:已使用
enum Either2.当我完成这项工作后,我将努力更新wiki页面上的限制,并为cookbook文章提供一个序列。非常感谢,感谢您为我指出初始化宏和伟大的解释,甚至是提供一些代码的努力。非常感谢!!@:genericBuild()和Rest是一个非常好的解决方案!上帝,我爱哈克斯:-)
--macro Macro.init()
import haxe.macro.Context;
class Macro {
public static function init() {
for (i in 2...11) {
Context.defineType({
pack: [],
name: "Either" + i,
pos: Context.currentPos(),
kind: TDEnum,
fields: [
for (j in 0...i) {
name: "_" + (j + 1),
kind: FFun({
args: [
{
name: "value",
type: TPath({
name: String.fromCharCode(65 + j),
pack: []
})
}
],
ret: null,
expr: null
}),
pos: Context.currentPos()
}
],
params: [
for (j in 0...i) {
name: String.fromCharCode(65 + j)
}
]
});
}
}
}
@:used
enum Either2<A : Either2.A,B : Either2.B> {
_1(value:Either2.A);
_2(value:Either2.B);
}