CTFE calling a template: Error: expression ... is not a valid template value argument

Jonathan M Davis jmdavisProg at gmx.com
Fri Sep 21 03:02:11 PDT 2012


On Friday, September 21, 2012 10:44:11 Jens Mueller wrote:
> Is it also illegal to do
> 
> int foo(char[] s) {
>   if (__ctfe)
>     return mixin(s);
>   else
>     return ""; // or assert(false)
> }
> 
> ?
> 
> Because this is executable at run time.

It's not executable at runtime. The __ctfe branch may very well be optimized 
out when compiled for runtime, but that doesn't mean that the code in it can 
be invalid. The function must be fully compiled in either case. Removing the 
__ctfe branch would merely be an optimization. It's an if after all, not a 
static if (and __ctfe can't be used in static if).

> > Normal recursion avoids this, because it only depends on the function's
> > signature, but what you're doing requires that the function be _run_ as
> > part of the process of defining it. That's an unbreakable circular
> > dependency and will never work. You need to redesign your code so that
> > you don't require a function to call itself while it's being defined.
> > Being called at compile time is fine, but being called while it's being
> > compiled is not.
> 
> But if the function wasn't compiled but interpreted at compile time it
> would be possible, wouldn't it?

D isn't an intepreted language, and I expect that trying to treat it at such 
would complicate things considerably. All CTFE does is make it possible to run 
functions at compile time in order to initialize stuff which must be known at 
compile time (which does include the possibility of doing stuff like passing 
function results as template arguments). It doesn't fundamentally change how 
things work. If anything, it's _more_ restrictive, not less. So, I don't think 
that it makes any sense at all to try and make it act in an interpretive 
fashion.

- Jonathan M Davis


More information about the Digitalmars-d mailing list