CTFE vs. traditional metaprogramming

Don nospam at nospam.com
Mon Oct 12 05:01:59 PDT 2009


language_fan wrote:
> Mon, 12 Oct 2009 12:07:19 +0200, Don thusly wrote:
> 
>> language_fan wrote:
>>> Sat, 10 Oct 2009 10:30:31 +0200, Don thusly wrote:
>>>
>>>> The more fundamental problem is that you can't instantiate a template
>>>> from inside CTFE. IE, you can cross from the "compile-time world" to
>>>> the "runtime world" only once -- you can never get back.
>>> That's not exactly true. Also both templates and CTFE are compile time
>>> features. You can compute a value with CTFE in the "value world" and
>>> lift the result to the "type world" with a template.
>> Yes, but the problem is that variables inside a CTFE function, even
>> though they are known at compile-time, are not permitted to be used as
>> template value parameters. For example:
>>
>> template A(int X) { enum int A = B(X)+1; } // OK, template can call CTFE
>>
>> int B(int X) { return A!(X) + 1; }
>>      // Not OK, CTFE cannot call template.
> 
> As far as I can tell there is no reason why you cannot call templates 
> from a CTFE code. Your code above has two problems: a) it never 
> terminates 

It wasn't meant to be a compilable example.

b) due to some lookup problem the compiler gets confused, this
> has nothing to do with CTFE not being able to call templates - for 
> instance this works:
> 
>> template A(int X) { enum int A = 2+1; }
>>
>> int B(int X) { return A!(X) + 1; }

You're seeing a few bugs there. In the template X isn't a constant, it's 
an alias (that is NOT in the spec, bug 2962). If you try adding a 
"static assert(X!=2)", you'll find it's not a constant.
It will let you write:  enum int A = X + 1; but that's bug 2414.

The rule is, any CTFE function must also be evaluatable at run-time. 
Templates cannot be instantiated at run-time.
Therefore templates cannot be instantiated in CTFE.






More information about the Digitalmars-d mailing list