D 中的编译时版本比较

Compile-time version comparison in D

我想要编译时(因为要在static if中使用)比较D.

中的版本字符串

例如 1.2.12 大于 1.2.2。我想在编译时做这样的比较。

编写一个在运行时运行的函数。然后调用它。类似于:

bool less(string a, string b)
{
  auto ap = a.splitter(".").map!(x => to!int(x));
  auto bp = b.splitter(".").map!(x => to!int(x));
  while (!ap.empty && !bp.empty)
  {
    if (ap.front < bp.front) return true;
    ap.popFront; bp.popFront;
  }
  return ap.empty;
}
static if (less("1.2.12", "1.2.2"))
  pragma(msg, "it's less");
else
  pragma(msg, "it's not less");

您可以在编译时调用普通函数。这就是我们在 D 中所说的 CTFE(编译时函数求值)。

引用 Walter Bright(从我的记忆中)"D has the unique ability to run D code at compile time"。