www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Allow illegal code in enum initialization?

reply "simendsjo" <simendsjo gmail.com> writes:
Illegal code is accepted in static if, but not in enum 
declarations. This leads to having three lines when one is 
enough. Is this just an oversight, or by design?

template T(alias A) {
     enum T = true;
}

void main() {
     struct S { }
     static if(__traits(compiles, S.a) && T!(S.a)) // ok
         enum e1 = true;
     else
         enum e1 = false;
     enum e2 = __traits(compiles, S.a) && T!(S.a); // No property 
S.a
}
Oct 23 2013
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 10/23/2013 02:55 AM, simendsjo wrote:
 Illegal code is accepted in static if, but not in enum declarations.
 This leads to having three lines when one is enough. Is this just an
 oversight, or by design?

 template T(alias A) {
      enum T = true;
 }

 void main() {
      struct S { }
      static if(__traits(compiles, S.a) && T!(S.a)) // ok
          enum e1 = true;
      else
          enum e1 = false;
      enum e2 = __traits(compiles, S.a) && T!(S.a); // No property S.a
 }
I don't know whether it is even specified but it feels like a feature to me. Just like the shortcut behavior of runtime if helps with avoiding illegal memory accesses, this helps with avoiding illegal code altogether: // null access avoided if ((p !is null) && (p.member == 42)) // illegal code avoided static if (__traits(compiles, S.a) && (S.a == 42)) Ali
Oct 23 2013
parent "simendsjo" <simendsjo gmail.com> writes:
On Wednesday, 23 October 2013 at 16:27:47 UTC, Ali Çehreli wrote:
 On 10/23/2013 02:55 AM, simendsjo wrote:
 Illegal code is accepted in static if, but not in enum 
 declarations.
 This leads to having three lines when one is enough. Is this 
 just an
 oversight, or by design?

 template T(alias A) {
     enum T = true;
 }

 void main() {
     struct S { }
     static if(__traits(compiles, S.a) && T!(S.a)) // ok
         enum e1 = true;
     else
         enum e1 = false;
     enum e2 = __traits(compiles, S.a) && T!(S.a); // No 
 property S.a
 }
I don't know whether it is even specified but it feels like a feature to me. Just like the shortcut behavior of runtime if helps with avoiding illegal memory accesses, this helps with avoiding illegal code altogether: // null access avoided if ((p !is null) && (p.member == 42)) // illegal code avoided static if (__traits(compiles, S.a) && (S.a == 42)) Ali
The question is if it would make sense to allow it for enum as well as static if. As enum is a compile-time constant I think it would be consistent.
Oct 23 2013