On Tue, Jun 2, 2009 at 12:03 PM, Chris Williams
<[email protected]> wrote:
> I would like to do something similar to the example at:
>
> http://www.digitalmars.com/d/1.0/mixin.html
>
> I want to create a class dynamically, but I want to be able to add an
> unspecified number of items to it. Pseudo-code, but something like this:
>
> template ClassGen(char[] className, char[][][] classMembers) {
> const char[] ClassGen = "class " ~ className ~ " {";
> for (int i = 0; i < classMembers.length; i++) {
> classGen ~= classMembers[i][0] ~ " " ~ classMembers[i][1] ~ ";"
> }
> classGen ~= "}";
> }
>
> mixin(
> ClassGen!(
> "Foo",
> [
> ["int", "bar"],
> ["int", "baz"]
> ]
> )
> );
>
> It seems like somehow between templates, mixins, and tuples (tuple arrays?)
> that something like this should be possible, but I'm still figuring out the
> language.
You'll be happy to know that your code compiles and works with very
little modification.
char[] ClassGen(char[] className, char[][][] classMembers) {
char[] ret = "class " ~ className ~ " {";
foreach(member; classMembers)
ret ~= member[0] ~ " " ~ member[1] ~ ";";
return ret ~ "}";
}
mixin(
ClassGen(
"Foo",
[
["int", "bar"],
["int", "baz"]
]
)
);
You can't use for loops in templates, so instead you have to use
recursion. In this case, however, a CTFE function is much terser.