Static if expression in D?

Viewed 93

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

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

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.

2 Answers

Since static if doesn't create a new scope, you can just do this:

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

// Use foo here as normal
foo.fun();

If you really want it to be an expression, you can do this:

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

auto foo = ifThen!(cond, altA, altB);

There are some limitations of alias parameters that may make this solution suboptimal, so it may or may not work for you.

It's been a long time since I coded in D, but did you try this as a workaround?

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

Contrary to C++, this is legal in D

Related