CTFE & enums & static assert

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 15 10:26:50 PDT 2015


On 05/15/2015 09:45 AM, Robert M. Münch wrote:

 > On 2015-05-04 18:22:17 +0000, Ali Çehreli said:

 >> TypeTuple is great because it enables "compile-time foreach"
 >> (unfortunately, implicitly):
 >>
 >>      foreach (m; __traits(allMembers, A)) {
 >>          // This body is repeated for each member at compile time
 >>      }
 >
 > Is there a way I can build an ENUM from within the FOREACH? What I want
 > to achive is, that I would like to use:
 >
 > final switch (myEnum) ...

Sorry, I don't understand your question. :(

Do you want to define an enum at compile time? Then you can use mixins.

Do you want to build an enum value inside the foreach? Yes, it is 
possible as well.

 > and have myEnum build at compiletime. With this the compiler would give
 > an error whenever I have forgotten to update my code to handle a new 
case.

I need a code example. Sorry. :(

 >>  > 2. I'm wondering why members1 doesn't has a type at all.
 >>
 >> Because it is a TypeTuple of values of various types and even types
 >> themselves.
 >
 > But shouldn't be the type than be "TypeTuple"?

A TypeTuple can contain types and values, which can be checked at 
compile time:

import std.stdio;
import std.typetuple;

// A function template
void foo(T...)()
{
     foreach (i, a; T) {
         static if (is (a)) {
             writefln("Argument %s is a type: %s", i, a.stringof);

         } else {
             writefln("Argument %s is not   : %s", i, a.stringof);
         }
     }
}

// Another one:
void bar(T, size_t N)()
{
     T[N] arr;
}

void main()
{
     alias args = TypeTuple!(int, 42);

     foo!args();
     bar!args();
}

Ali



More information about the Digitalmars-d-learn mailing list