【问题标题】:Joining strings at compile time在编译时加入字符串
【发布时间】:2013-03-01 11:28:33
【问题描述】:

我想在编译时加入文件名和图像格式。 以下示例不起作用,因为我想在编译时无法评估 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()。错误如何解决?

【问题讨论】:

    标签: arrays string d ctfe


    【解决方案1】:

    你有点过于复杂了。

    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 有很多不同的编译时任务工具。

    【讨论】:

    • 真正让我无法使用普通函数的是,我最初也在正文中使用了import,我想这在普通函数中不起作用。不过谢谢你的掌声时刻。
    • 导入确实在函数中起作用,但它是几个版本前的新功能。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 2021-02-24
      • 2011-10-19
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 2013-11-07
      • 2021-11-18
      相关资源
      最近更新 更多