4

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

4

3 回答 3

5

也许使用字符串混合?

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)
于 2015-10-06T09:59:52.560 回答
3

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

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;
于 2015-10-06T20:14:56.140 回答
3

@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;
于 2015-10-07T05:58:10.993 回答