我可以在编译时连接 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);
}
此代码返回错误
Error: variable f cannot be read at compile time
。功能方法似乎也不起作用:
enum files = ["a.txt", "b.txt"];
enum result = reduce!((a, b) => a ~ import(b))("", files);
它返回相同的错误:
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)
关于d - 从数组中定义的文件名导入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966478/