CTFE question

Philippe Sigaud philippe.sigaud at gmail.com
Tue Aug 28 10:40:08 PDT 2012


On Tue, Aug 28, 2012 at 2:07 PM, Chris Cain <clcain at uncg.edu> wrote:
> On Tuesday, 28 August 2012 at 11:39:20 UTC, Danny Arends wrote:
>>
>> Ahhh I understand...
>>
>> As a follow up, is it then possible to 'track' filling a
>> large enum / immutable on compile time by outputting a msg
>> every for ?
>>
>> I'm generating rotation matrices for yaw, pitch and roll
>> at compile time which can take a long time depending on
>> how fine grained I create them.
>
>
> I'm pretty sure there isn't. However, if you're just trying to develop/test
> your algorithm, you could write a program that runs it as a normal function
> (and just use writeln) as you develop it. After it's done, you remove the
> writelns, mark the function as pure and it should work exactly the same in
> CTFE.

Godd adivce, except beware of using ++ and --, they don't work at
compile-time. I'm regularly caught unaware by this, particularly while
looping.


Danny is also using 0..360, which is a runtime value. There exists a
compile-time version of foreach which is automatically invoked
whenever you use foreach on a compile-time 'range' (aka, typetuple)

So:

template Loop(T...)
{
    /* some code */
    foreach(i,Type; T)
        pragma(msg, i);
}

will work.

So, a way to get what the OP wanted is to create a tuple of the
required length. Since integers are valid template arguments, we can
use them directly like this:

template staticRange(uint upto)
{
    static if (upto == 0)
        alias TypeTuple!() staticRange;
    else
        alias TypeTuple!(staticRange!(upto-1), upto-1) staticRange;
}

So staticRange!3 is the tuple 0,1,2. (staticRange!0 is empty)
You can foreach on it:

pure int[] testCTFE(){
  int[] r;
  pragma(msg, "Testing CTFE");

  foreach(i; staticRange!360){
    r ~= i;
    pragma(msg, i);
  }

  pragma(msg, "Done CTFE test");
  return r;
}


Of course, that means knowing the upper value at compile-time.


More information about the Digitalmars-d-learn mailing list