[D1] struct opEquals questions

bearophile bearophileHUGS at lycos.com
Thu Mar 18 13:51:11 PDT 2010


Inside free functions there can be a locally defined compile-time boolean constant like __used_return. If you use this constant inside a function the compiler creates two versions of the function that share the same static variables (if the function is a template then each pair of instantiated functions share the same static variables). Inside the function you can use a static if to not compute the return value if __used_return is false (so in this case the function has void return type).

qwerty:
>   if compiler doesn't know --> point to returnCalc version
>   if called through pointer --> point to returnCalc version 

Yes, the default has to be __used_return = true. But I don't know if this is safe enough.


So this:


int foo(int x) {
    int val;
    val += x;
    static if (__used_return)
        return val + 1;
}
void main() {
    int y = foo(5);
    foo(6);
    int function(int) tf = &foo;
    alias typeof(foo) TF;
}



Once desugared is like:

int _foo_val;
int foo_ret(int x) {
    _foo_val += x;
    return _foo_val + 1;
}
void foo_void(int x) {
    _foo_val += x;
}
void main() {
    int y = foo_ret(5);
    foo_void(6);
    int function(int) tf = &foo_ret;
    alias typeof(foo_ret) TF;
}


In practice I don't think this can be useful enough.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list