__traits getMember is context sensetive?

JDemler via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 13 16:55:53 PDT 2015


On Saturday, 13 June 2015 at 23:51:32 UTC, JDemler wrote:
> I have another one :)
>
> module test;
>
> struct S{
>   string member1;
>   int member2;
> }
>
> string test(string[] a)
> {
>   const S s = { member1:"It is also important to go to Mars!"};
>   const string y = a[0];
>   return y;
> }
>
> void main()
> {
>   enum e = ["member1","member2"];
>   pragma(msg, e[0]);
>   pragma(msg, test(e));
> }
>
> Compiles, works fine while
>
> module test;
>
> struct S{
>   string member1;
>   int member2;
> }
>
> string test(string[] a)
> {
>   const S s = { member1:"It is also important to go to Mars!"};
>   const string y = a[0];
>   return __traits(getMember, s, y);
> }
>
> void main()
> {
>   enum e = ["member1","member2"];
>   pragma(msg, e[0]);
>   pragma(msg, test(e));
> }
>
> spits out following:
>
> test.d(11): Error: variable a cannot be read at compile time
> test.d(12):        while evaluating y.init
> test.d(12): Error: string expected as second argument of 
> __traits getMember instead of __error
> test.d(12): Error: cannot implicitly convert expression (false) 
> of type bool to string
> member1
> test.d(19): Error: CTFE failed because of previous errors in 
> test
> test.d(19):        while evaluating pragma(msg, 
> test(["member1", "member2"]))
>
> If i use "member1" directly it works.
>
> What am I missing here?
>
> Thanks for your help

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.

Is there a workaround for that?




More information about the Digitalmars-d-learn mailing list