我可以import在编译期间连接读取的文件,如下所示:
enum string a = import("a.txt");
enum string b = import("b.txt");
enum string result = a ~ b;
Run Code Online (Sandbox Code Playgroud)
result如果我在数组中有文件名,我怎么能得到连接?
enum files = ["a.txt", "b.txt"];
string result;
foreach (f; files) {
  result ~= import(f);
}
Run Code Online (Sandbox Code Playgroud)
此代码返回错误Error: variable f cannot be read at compile time.
功能方法似乎也不起作用:
enum files = ["a.txt", "b.txt"];
enum result = reduce!((a, b) => a ~ import(b))("", files);
Run Code Online (Sandbox Code Playgroud)
它返回相同的错误: Error: variable b cannot be read at compile time
也许使用字符串mixins?
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)
Run Code Online (Sandbox Code Playgroud)