从数组中定义的文件名导入内容

Import content from filenames defined in an array

我可以像这样在编译期间连接 import 读取的文件:

enum string a = import("a.txt");
enum string b = import("b.txt");
enum string result = a ~ b;

如果文件名在一个数组中,我如何获得串联的 result

enum files = ["a.txt", "b.txt"];
string result;
foreach (f; files) {
  result ~= import(f);
}

此代码 returns 有错误 Error: variable f cannot be read at compile time

函数式方法似乎也不起作用:

enum files = ["a.txt", "b.txt"];
enum result = reduce!((a, b) => a ~ import(b))("", files);

它returns有同样的错误:Error: variable b cannot be read at compile time

也许使用字符串混合?

enum files  = ["test1", "test2", "test3"];

// There may be a better trick than passing the variable name here
string importer(string[] files, string bufferName) {
    string result = "static immutable " ~ bufferName ~ " = ";

    foreach (file ; files[0..$-1])
        result ~= "import(\"" ~ file ~ "\") ~ ";
    result ~= "import(\"" ~ files[$-1] ~ "\");";

    return result;
}

pragma(msg, importer(files, "result"));
// static immutable result = import("test1") ~ import("test2") ~ import("test3");

mixin(importer(files, "result"));
pragma(msg, result)

我找到了一个不使用字符串混合的解决方案:

string getit(string[] a)() if (a.length > 0) {
    return import(a[0]) ~ getit!(a[1..$]);
}

string getit(string[] a)() if (a.length == 0) {
    return "";
}

enum files = ["a.txt", "b.txt"];
enum result = getit!files;

@Tamas 回答。

从技术上讲,可以使用 static if 将其包装到一个函数中,我认为这看起来更干净。

string getit(string[] a)() {
    static if (a.length > 0) {
        return import(a[0]) ~ getit!(a[1..$]);
    }
    else {
        return "";
    }
}

技术上也是

static if (a.length > 0)

可能是

static if (a.length)

您也可以像这样解释未初始化的数组

string getit(string[] a)() {
    static if (a && a.length) {
        return import(a[0]) ~ getit!(a[1..$]);
    }
    else {
        return "";
    }
}

用法仍然相同。

enum files = ["a.txt", "b.txt"];
enum result = getit!files;