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

标签 d ctfe

我可以在编译时连接 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/

相关文章:

constants - D 中的逻辑常量

c++ - 对特定 CPU 进行基准测试和限制执行

d - 开始使用 gtkd

D 特征 - 完整数据成员列表

attributes - UDA opCall __traits

regex - 在 D 中的编译时评估正则表达式

reflection - D语言: Iterate over members of a struct and check a UDA (runtime reflection)

d - 在静态类型语言 D 中使用动态类型