Compile time function execution...
Michiel
nomail at please.com
Thu Feb 15 11:17:19 PST 2007
Walter Bright wrote:
> ... is now in DMD 1.006. For example:
>
>> -------------------------------------------
>> import std.stdio;
>>
>> real sqrt(real x)
>> {
>> real root = x / 2;
>> for (int ntries = 0; ntries < 5; ntries++)
>> {
>> if (root * root - x == 0)
>> break;
>> root = (root + x / root) / 2;
>> }
>> return root;
>> }
>>
>> void main()
>> {
>> static x = sqrt(10); // woo-hoo! set to 3.16228 at compile time!
>> writefln("%s, %s", x, sqrt(10)); // this sqrt(10) runs at run time
>> }
>> ------------------------------------------
>
> This should obsolete using templates to compute values at compile time.
That's a great feature! A couple of questions, if I may:
* Can sqrt still call another function?
* Does it still work if classes or structs are involved in any way? What
about enums? What about arrays?
* Why is the second sqrt(10) run at runtime? In theory it's still a
constant, right? Is this something that will work in a later version?
Congrats on the new feature!
More information about the Digitalmars-d
mailing list