Compile time function execution...

Lionello Lunesu lio at lunesu.remove.com
Fri Feb 16 00:22:45 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.

Can I use the results of compile-time evaluatable functions in "static 
if", "pragma(msg)" ? This makes D a scripting language :)


// This does not (yet) work though:
bool func() { return true; }

static if (func()) {
pragma(msg, "true" );
} else {
pragma(msg, "false" );
}


L.



More information about the Digitalmars-d mailing list