Can you do this in D?

David Piepgrass qwertie256 at gmail.com
Thu Jul 26 10:35:56 PDT 2012


> 3. Is there any way of executing code or programs during compile
> time?
> I've seen an example of CTFE (Compile Time Function Evaluation),
> although I'm unsure if this works for stuff like classes.
> However, I am considering more advanced execution (not 
> constants)
> such as printing to a file during compiling for stuff like how
> long compiling a certain function/template takes.

You can call any safe and pure D code at compile time (none of 
the code has to be marked pure explicitly, but it cannot access 
any static or global variables, call C code, access files, etc.) 
This is called CTFE=Compile-Time Function Evaluation.

The "pure" limitation isn't a huge restriction, since you can 
still edit member variables (fields) and the compiler can memoize 
the results of CTFE... although I don't know if it memoizes 
automatically, or if you have to use a template to accomplish it. 
For example if I do

enum twoPi = computePi() + computePi();

I don't know if the compiler computes PI once or twice. Does 
someone know? But if I define this template:

@property auto memoize(T, T code)() { return code; }

enum twoPi = memoize!(double,computePi()) + 
memoize!(double,computePi());

Then computePi is surely called only once, and thus you can cache 
the result of any computation for repeated use. (I don't know how 
to get the type 'double' to be inferred automatically, though.) 
You can also, of course, use enums for this purpose:

enum pi = computePi(); // computed only once
enum twoPi = pi + pi;

I don't think you can run "programs" at compile-time, but since 
you can call ordinary functions and use arbitrarily large 
structs, you can accomplish a lot. I believe the current released 
build, 2.059, can't use classes at compile time, but bearophile 
just implied that 2.060 can.

> 5. Why not support other operators like $, #, and @?
> This is more of a rhetorical... as I know the language doesn't
> need them, nor would I know if they would be binary/unary
> prefix/etc or the precedence... although they would be nice to
> have. Specifically I'd like $prefix to be stringification.

Just to clarify, because other people are making it sound like D 
could do this... no, D does not offer user-defined operators, 
only overloading of predefined operators. User-defined ops would 
certainly be a nice feature that I would like to have, but the D 
developers have too much to do already. Personally I think the D 
syntax and rules feel too ad-hoc and unintuitive right now; it 
should be simplified slightly, formalized more clearly, and 
debugged further before yet more features are piled on.


More information about the Digitalmars-d mailing list