Static if expression in D?

Fil*_*und 3 d

How can I simulate a static if expression (not statement) in D?

auto foo = (({ static if (cond) { return altA; } else { return altB; })());
Run Code Online (Sandbox Code Playgroud)

This works, but creates a delegate and ldc errors out if you nest delegates. I'm sure it can be done as an expr with some template magic, I'm just not good enough at it yet.

小智 5

由于static if不会创建新范围,您可以这样做:

static if (cond)
    auto foo = altA;
else
    auto foo = altB;

// Use foo here as normal
foo.fun();
Run Code Online (Sandbox Code Playgroud)

如果你真的希望它是一个表达式,你可以这样做:

template ifThen(bool b, alias a, alias b) {
    static if (b)
        alias ifThen = a;
    else
        alias ifThen = b;
}

auto foo = ifThen!(cond, altA, altB);
Run Code Online (Sandbox Code Playgroud)

alias参数的一些限制可能会使此解决方案不理想,因此它可能适合您,也可能不适合。