How far can CTFE go?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 3 19:10:22 PST 2012


On Sat, Feb 04, 2012 at 02:36:10AM +0000, Manfred Nowak wrote:
[...]
> > - better syntax, can do complex things without obfuscating the
> > code 
> If the codes for more than one _needed_ phase are tangled into one
> code base, I call that an "obfuscated" base. 
[...]

One major advantage of CTFE that is covered in TDPL is compile-time
validation of generated code. The example was generating a linear
congruential engine for generating random numbers. The CTFE is used not
only for generating the congruential engine code, but also to validate
that its generating parameters do not lead to poor behaviour such as a
very short period.

If this was code generated by an external utility, you cannot easily
validate the resulting code. Worse yet, the external utility generates
correct code (e.g. a linear congruential generator with a maximal
period) but the user goes and edits one of the parameters, it turns into
a generator with a bad period. There's no easy way to prevent this.
With CTFE, all generated linear congruential generators are *guaranteed*
to have maximal periods, because the CTFE simply refuses to generate
something with bad parameters.

Also, functions used in CTFE can *also* be used at runtime. If you were
forced to generate code by an external utility, there may not be a nice
way of reusing code in this way, and there's the possibility that you
will accidentally end up using two different versions of the function,
leading to subtle hard-to-find bugs. With CTFE, it is guaranteed that
the function used to generate the compile-time data is exactly the same
as the one that is used at runtime to generate other data.


T

-- 
There are 10 kinds of people in the world: those who can count in binary, and those who can't.


More information about the Digitalmars-d-learn mailing list