1

我想在编译时加入文件名和图像格式。以下示例不起作用,因为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;
    }
}

它失败并显示错误消息:

Error: arithmetic/string type expected for value-parameter, not string[]

我需要将其最终输入import(). 如何解决错误?

4

2 回答 2

5

你有点过于复杂了。

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() {}

或在 DPaste 上查看:http: //dpaste.1azy.net/7b42daf6

如果提供的代码中有不清楚的地方,或者您坚持使用其他方法 - 请在此处发表评论。D 有很多不同的编译时任务工具。

于 2013-03-01T15:53:57.977 回答
0

经过进一步搜索,它出现了http://forum.dlang.org/post/jezkyrguyoshofciuxjq@forum.dlang.org。这是 DMD 2.061 中的一个错误,解决方法是将文件名声明为alias.

于 2013-03-01T12:09:06.500 回答