2015-10-06 39 views
4

我可以连接文件在编译时是这样的:导入内容由<code>import</code>阅读

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

回答

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; 
+0

简单干净...我更喜欢这个解决方案,我的! – cym13

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) 
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;