digitalmars.D.learn - class templates and static if
- Tyler Jameson Little (36/36) Feb 26 2012 So, here's my code, as it stands currently:
So, here's my code, as it stands currently: import std.stdio; static enum Type { request, response }; class Parser(Type t) { static if (t == Type.request) { string name = "request"; } else { string name = "response"; } string message; this(string message) { this.message = message; } } void main() { immutable Type t = Type.request; Parser!t h = new Parser!t("Hello world"); writefln("%s: %s", h.name, h.message); } The general goal is to make a templated class that will only include the parts that each needs. I would like to keep this all as one class template, because there is a lot of shared code, and I would like to keep it as seamless as possible and not have to separate out code into separate functions. Anyway, my current approach is a little clunky, because it requires an immutable to be created just to tell the compiler what type of parser I need. I was thinking about having two classes, Request and Response, and have parser take a normal template (class Parser (T)), but I wanted to restrict it to just those two classes (for now), so I came up with the enum solution. Is there a better way to do this? What I'd ultimately like to do is have some static if surrounding blocks of code that depends on the input to the template.
Feb 26 2012