Seb*_*raf 1 arrays string d ctfe
我想在编译时加入文件名和图像格式.以下示例不起作用,因为string[]无法在编译时评估我想...
immutable imageFormats = ["bmp", "jpg", "gif", "png"];
template fileNamesWithImageFormat(string[] fileNames)
{
string[] fileNamesWithImageFormat() {
string[] ret;
ret.length = imageFormats.length * fileNames.length;
for (int j = 0; j < fileNames.length) {
for (int i = 0; i < imageFormats.length; ++i) {
ret[j * fileNames.length + i] = fileNames[j] ~ "." ~ imageFormats[i];
}
}
return ret;
}
}
Run Code Online (Sandbox Code Playgroud)
它失败并显示错误消息:
Error: arithmetic/string type expected for value-parameter, not string[]
Run Code Online (Sandbox Code Playgroud)
我需要最终加入import().如何解决错误?
你有点过于复杂了.
CTFE(编译时功能执行)应该适合这里.您可以编写处理string[]输入的常用函数,并在编译时表达式中使用它.有一些限制,但您的代码非常适合CTFE,因此不需要模板.
您的索引中也有轻微错误.在编译时工作的更正版本:
import std.algorithm, std.array, std.range;
import std.stdio;
string[] modify(string[] names)
{
if (!__ctfe)
assert(false);
immutable string[] imageFormats = ["bmp", "jpg", "gif", "png"];
string[] ret;
ret.length = imageFormats.length * names.length;
for (int j = 0; j < names.length; ++j) {
for (int i = 0; i < imageFormats.length; ++i) {
ret[j * imageFormats.length + i] = names[j] ~ "." ~ imageFormats[i];
}
}
return ret;
}
enum string[] input = ["one", "two"];
pragma(msg, modify(input));
void main() {}
Run Code Online (Sandbox Code Playgroud)
或者在DPaste上查看:http://dpaste.1azy.net/7b42daf6
如果提供的代码中的某些内容不清楚或您坚持使用其他方法 - 请在此处发表评论.D有许多不同的编译时任务工具.