mixin 模板:如何停止编译?
mixin templates: how to halt compilation?
我有一个 mixin 模板,它只对某些参数有效。如果参数无效,我想用错误消息停止编译。对于模板,我会使用 assert(false, "Invalid args for Yoo")
但这不适用于混合模板。如何停止下面示例的编译?
mixin template Yoo(args...) {
static if (args.length == 0) {
pragma(msg, "Invalid args! (how to halt the compilation?)");
} else {
pragma(msg, "Valid args:", args);
}
}
void main() {
mixin Yoo;
mixin Yoo!(1,2,3);
}
你可以做到
static assert(0, "Invalid args!");
而不是 pragma 消息。静态断言就像 assert
,只是编译时,它不会在发布模式下被删除,因为它只在编译时检查并且不包含在编译代码中。
static assert
的替代方法是模板约束:
mixin template Yoo(args...) if (args.length > 0) {
使用上面的方法,Yoo!()
将无法编译并显示类似
的消息
Error: mixin d.Yoo!() does not match template declaration Yoo(args...) if (args.length > 0)
这样做的好处是,如果其他人需要,他们可以定义自己的
拥有 Yoo
不接受任何参数。使用 static assert
且没有模板
约束,它们的定义会冲突。
但是,static assert
确实可以让您提供更有帮助的消息。
我有一个 mixin 模板,它只对某些参数有效。如果参数无效,我想用错误消息停止编译。对于模板,我会使用 assert(false, "Invalid args for Yoo")
但这不适用于混合模板。如何停止下面示例的编译?
mixin template Yoo(args...) {
static if (args.length == 0) {
pragma(msg, "Invalid args! (how to halt the compilation?)");
} else {
pragma(msg, "Valid args:", args);
}
}
void main() {
mixin Yoo;
mixin Yoo!(1,2,3);
}
你可以做到
static assert(0, "Invalid args!");
而不是 pragma 消息。静态断言就像 assert
,只是编译时,它不会在发布模式下被删除,因为它只在编译时检查并且不包含在编译代码中。
static assert
的替代方法是模板约束:
mixin template Yoo(args...) if (args.length > 0) {
使用上面的方法,Yoo!()
将无法编译并显示类似
Error: mixin d.Yoo!() does not match template declaration Yoo(args...) if (args.length > 0)
这样做的好处是,如果其他人需要,他们可以定义自己的
拥有 Yoo
不接受任何参数。使用 static assert
且没有模板
约束,它们的定义会冲突。
但是,static assert
确实可以让您提供更有帮助的消息。