CTFE vs. traditional metaprogramming
Denis Koroskin
2korden at gmail.com
Mon Oct 12 05:06:50 PDT 2009
On Mon, 12 Oct 2009 16:01:59 +0400, Don <nospam at nospam.com> wrote:
> 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.
>
I believe you mean "Templates that depend on arguments passed to a
function cannot be instantiated". It doesn't mean you can't used templates
in CTFE at all.
More information about the Digitalmars-d
mailing list