structaliasdtemplate-meta-programmingctfe

Using CTFE to Generate Set of struct aliases


Say I have a class

struct Vector (ElementType, uint Dimension) { ... }

representing a fixed-dimensional vector along with these shorthands

alias Vector!(float, 2) vec2;
alias Vector!(float, 3) vec3;
alias Vector!(float, 4) vec4;
alias Vector!(double, 2) vec2d;
alias Vector!(double, 3) vec3d;
alias Vector!(double, 4) vec4d;
alias Vector!(int, 2) vec2i;
alias Vector!(int, 3) vec3i;
alias Vector!(int, 4) vec4i;

can I somehow use D's features to generates these aliases in compile time?

Or is it just for evaluation of functions?

/Per


Solution

  • You could always do it as a mixin.

    string makeAliases() {
       string code;
       import std.conv;
    
       foreach(type; ["float", "double", "int"])
       foreach(n; 2 .. 5)
          code ~= "alias Vector!("~type~", " ~ to!string(n) ~ ") vec" ~   to!string(n) ~ type[0] ~ ";\n";
    
      return code;
    }
    
    mixin(makeAliases());
    

    Generally, if you make a compile time evaluatable function that builds a string of code, you can then mixin(thatFunction(args...)); at some point and make it happen.

    When debugging the function, you can just run it at runtime and writeln(thatFunction()) to see what code it generates.