What's equivalent to C#'s select?

Simen Kjærås simen.kjaras at gmail.com
Mon Jan 15 07:37:42 UTC 2018


On Sunday, 14 January 2018 at 22:07:22 UTC, Marc wrote:
> thanks, can i use it at compile time as well?
>
>>	enum isMutableString(string field) = 
>>is(typeof(__traits(getMember, >C, field)) == string);
>>	static foreach(field; [FieldNameTuple!C].filter!(f =>
>>>isMutableString!(f))) {
>>		writeln(field);
>>	}

You're mixing compile-time and run-time logic here in a way that 
D doesn't allow. In particular, isMutableString requires the 
passed string to be a compile-time constant, and filter works on 
run-time values.

There are a few different ways to resolve this. First, std.meta 
has the Filter template, which behaves much in the same way as 
std.algorithm.filter, but with compile-time tuples:

static foreach (field; Filter!(isMutableString, 
FieldNameTuple!C)) {
     writeln(field);
}

The other option is to rewrite isMutableString to work with 
run-time values:

bool isMutableString(string field) {
     switch (field) {
         foreach (cField; FieldNameTuple!C) {
             case cField:
                 return is(typeof(__traits(getMember, C, cField)) 
== string);
         }
         default:
             return false;
     }
}
static foreach(field; [FieldNameTuple!C].filter!(f => 
isMutableString(f))) {
     writeln(field);
}

Both of these give the same output, and should be what you want.

--
   Simen


More information about the Digitalmars-d-learn mailing list