December 23, 2017
When I wanted something like

  static if (enum var = expr)
  { ... }

I did

  static foreach (enum var; { auto x = expr; return x ? [ x ] : [ ]; }())
  { ... }

The only drawback is, there is no `else`.

You can use the trick even for normal if when the condition is not identical to the expression of the declared variable:

  if (auto var = expr) // tests cast(bool)x
  { ... }

Same solution

  foreach (var; { auto x = expr; return cond ? [ x ] : [ ]; }())
  { ... }

Drawback apart from not having else: May allocate if the compiler doesn't optimize it. Even then, the code is not @nogc. One would use std.range.only for that:

  foreach (var; {
      import std.range : only;
      auto singleton = only(expr);
      if (!cond) singleton.popFront;
      return singleton;
    }())
  { ... }

This can be archived, too, by using std.iteration.filter:

  import std.range : only;
  import std.iteration : filter;
  foreach (var; singleton.only.filter!cond)
  { ... }

Has anyone encountered something similar?

Note that most of the time, you can put the declaration before the test. You cannot in mixin templates, where I needed it.