static foreach / iterate over all consts in a module?

Rubn where at is.this
Mon Mar 4 00:10:58 UTC 2019


On Sunday, 3 March 2019 at 19:20:00 UTC, Robert M. Münch wrote:
> If I want to iterate over all const WM_* windows message 
> definitions during compile time, can this be done with a static 
> foreach and the allMembers traits?
>
> Something like:
>
> static foreach(wm; __traits(allMembers, mymodule)) {
> 	static if(wm[1..3] == "WM_") {

Something like this? You can also use static foreach instead, but 
then you'll need to add another pair of `{}` brackets otherwise 
you'll get `member` is defined multiple times.

https://run.dlang.io/is/7legpv

module thisModule;

struct MW_ {}

const(MW_)* one;
const(MW_)* two;

void main()
{
     import std.stdio;

     foreach(memberName ; __traits(allMembers, thisModule))
     {
         alias member = __traits(getMember, thisModule, 
memberName);
         static if(is(typeof(member) : const(MW_)*)) {
             writeln(memberName, ": ", member);
         }
     }
}


More information about the Digitalmars-d mailing list