将 D 模板化结构作为通用类型处理
我在设计 D 应用程序时遇到了麻烦。也许我的做法是完全错误的,所以我来这里是为了让你来救我。欢迎任何建议,包括完全重写。
我有一些模板化类型:
enum Type : byte { Message='!', Integer='@' }
struct Token (T) {
Type type;
T value;
}
alias Token!string MessageToken;
alias Token!long IntegerToken;
并且我需要一般性地处理这些类型:
AnyToken genToken(bool cond) {
if (cond)
return MessageToken(Type.Message, "nighly builds");
else
return IntegerToken(Type.Integer, -42);
}
AnyToken a = genToken(true);
AnyToken b = genToken(false);
如何实现这种效果? 编辑: OOP 替代方案也受到欢迎。
I'm in trouble on designing a D app. Maybe my approach is completely wrong, so I come here to you rescue me. Any suggestion, including complete rewrite, is welcome.
I have some templated types:
enum Type : byte { Message='!', Integer='@' }
struct Token (T) {
Type type;
T value;
}
alias Token!string MessageToken;
alias Token!long IntegerToken;
And I need to handle these types generically:
AnyToken genToken(bool cond) {
if (cond)
return MessageToken(Type.Message, "nighly builds");
else
return IntegerToken(Type.Integer, -42);
}
AnyToken a = genToken(true);
AnyToken b = genToken(false);
How do I achieve this effect? Edit: OOP alternatives are welcome too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我自己使用了标记联合,
请注意它们之间没有静态(编译时)差异,但这几乎是没有继承的情况下最好的选择,
您可以添加一些额外的函数,这样它看起来更像继承,所以您不需要在结构函数之外检查类型字段
I'd have used a tagged union myself
note that there's no static (compile time) difference between them but it's pretty much the best on can do without inheritance
you can add some extra functions so it looks more like inheritance so you won't need to examine the type field so much outside the struct's functions
您可以使用 std.variant。
我无法想象另一种方式。最终它们是完全不同的类型。
You could use std.variant.
I can't imagine another way. In the end they are completely separate types.
如果您确实需要保留原始结构,那么您可以创建一个类层次结构,其中包装指向结构的指针并相应地进行分派。
If you really need to keep the original structs then you could create a hierarchy of classes that wrap a pointer to a struct and dispatch accordingly.