Thread overview
Complex Object Generation with Templates/Mixins
Jun 02, 2009
Chris Williams
Jun 02, 2009
Chris Williams
June 02, 2009
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.
June 02, 2009
On Tue, Jun 2, 2009 at 12:03 PM, Chris Williams <littleratblue@yahoo.co.jp> 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.
June 02, 2009
Jarrett Billingsley Wrote:
> 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.

Wonderful. Thank you.