2015-10-06 50 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;