Going from CTFE-land to Template-land

Bill Baxter wbaxter at gmail.com
Tue Nov 17 08:52:43 PST 2009


On Tue, Nov 17, 2009 at 7:07 AM, Don <nospam at nospam.com> wrote:
> Bill Baxter wrote:
>>
>> Currently this doesn't work, because the CTFE function doesn't "know"
>> that it's running compile-time:
>>
>> int templ_incr(int x)() {
>>    return x+1;
>> }
>>
>> int ctfe_incr(int x) {
>>    return templ_incr!(x);
>> }
>>
>> Seems common to write a function that you know is only intended to be
>> used compile-time.
>> But it can't compile because the compiler doesn't know you only plan
>> to call it at compile-time.
>>
>> Is something version(__ctfe) might help with?  E.g.
>> version(__ctfe) {
>>    // only allow cfte_incr to be called at compile-time so it can use
>> templates
>>    int ctfe_incr(int x) {
>>        return templ_incr!(x);
>>    }
>> }
>
> No. Here's the only functionality you'll get. This works by exploiting bug
> 1330. It's inefficient: the inCTFE function gets called all the time. Should
> just be a bool value, which will be constant-folded away. Otherwise, it's
> the same as this:
>
> // true if evaluated in CTFE, false if called at runtime.
> bool inCTFE()
> {
>     int [1] x = [1];
>     int [] y = x;
>     y[0] = 2;
>     return x[0]!=2;
> }
>
> static assert(inCTFE());
>
> void main()
> {
>  assert(!inCTFE());
> }

After pondering it some more, I'm inclined to think CTFE->Template
calls are not really needed.

Templates are at their heart supposed to offer computations on types.
Sometimes types involve values, so they need to be able to do some
compute with values too.

CTFE on the other hand is all about doing compute on values.  So if
you're in a CTFE function you're definitely in value-land.  There
shouldn't be any reason to need to pass your CTFE values to a
template.  By definition you're only dealing with values, so you don't
need the type computation features of templates.

--bb



More information about the Digitalmars-d mailing list