__traits getMember is context sensetive?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 13 22:50:39 PDT 2015


On Sat, 13 Jun 2015 23:55:53 +0000, JDemler wrote:

> After a bit of rethinking:
> 
> I guess the compiler goes through 2 loops:
> the first resolves __traits, the second does ctfe.
> 
> That would explain this behavior. "a" is not present to the compiler
> while it tries to resolve my __traits call, but will be present in case
> of ctfe.

the thing is that `a` (and `s` for that matter) is a *runtime* variable. 
even if you can see that it will not change and effectively a constant, 
compiler doesn't see that and doesn't assume that it can use such 
constants in CTFE.

the difference is like this:

  enum s0 = "string0"; // compile time constant

  string s1 = "string1"; // runtime constant

compiler doesn't do data flow analysis to prove that s1 will never change 
and it can be used as compile time constant, it simply plays a crybaby 
here, complaining that it can't read runtime variable value in compile 
time.

here's what you can do instead:

  immutable S s = { member1:"It is also important to go to Mars!"};

  template test(string[] a) {
     enum y = a[0];
     enum test = __traits(getMember, s, y);
  }

  void main () {
     enum e = ["member1","member2"];
     pragma(msg, e[0]);
     pragma(msg, test!(e));
  }
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150614/2f8da1fa/attachment.sig>


More information about the Digitalmars-d-learn mailing list