Compile-time global mutables

Adam Ruppe destructionator at gmail.com
Thu Jun 30 13:47:47 UTC 2022


On Thursday, 30 June 2022 at 13:39:57 UTC, HuskyNator wrote:
> How would you write a static constructor that loads in all 
> files used somewhere in the source code? This seems like a 
> prerequisite to being able to do that.

template file(string name) {
     import yourproject.allfiles;

     shared static this() {
         allfiles ~= name;
     }

     enum file = name;
}


Use it like:

auto img = Image(file!"thing.jpg");


And then yourproject.allfiles module has:

__gshared string[] allfiles; // you MUST only write to it from 
those constructors but afterwards can iterate it since you know 
it is immutable from that point on


And somewhere in your main() function:


void main() {
     import yourpoject.allfiles;
     foreach(file; allfiles)
         loadFile(file);
}



Or similar. The key point is the magic `file` template builds an 
array of all files in its static constructors which you then 
process later at runtime.


More information about the Digitalmars-d mailing list