List classes at compile time

Noé Falzon falzon.noe at gmail.com
Sat Oct 19 08:51:20 UTC 2024


tl;dr: is it possible to iterate over all classes in a program at 
compile time (or possibly all derived classes from a given base 
class) to use in a mixin?

Longer version:

Hi! I'm essentially trying to select which class to 
instantiate/use as template argument based on a runtime string 
(user provided). Something like:

```
string s = args[1];
if (s == "foo") { import foo; return Driver!Foo.run(); }
if (s == "bar") { import bar; return Driver!Bar.run(); }
if (s == "baz") { import baz; return Driver!Baz.run(); }
...
```

Using mixins, I managed to reduce this to:

```
static foreach(name; ["Foo", "Bar", "Baz"])
{
mixin(iq{
if (s == "$(name.toLower)")
   {
     import $(name.toLower);
     return Driver!$(name).run();
   }
}.text);
}
```

But it would be even nicer not to have to list the classes by 
hand, of course (there might be hundreds eventually).

The closest I got so far is to generate the list of names with a 
pre-build command that greps through the sources for relevant 
class names, and a file import:

```
const names = import("names.csv").split(",");
```

But that feels like cheating, and it's of course error-prone 
since it's text based. Also, if I'm going to run a pre-build 
command, I might as well just generate the boilerplate source 
code there and just compile the file directly.

Would there a cleaner, D-like way to achieve this? Or a 
completely different approach to the problem?


More information about the Digitalmars-d-learn mailing list