Domanda

I want to join file names and image formats at compile time. The following example doesn't work, because string[] can't be evaluated at compile I suppose...

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

It fails with the error message:

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

I need this to be finally fed into import(). How can the error be resolved?

È stato utile?

Soluzione

You are over-complicating this a bit.

CTFE (Compile-Time Function Execution) should suit here. You can just write usual function that processes string[] input and use it in compile-time expressions. There are some limitations, but your code is pretty CTFE-ready, so there is no need for templates.

You have also minor error in your indexes. Corrected version that works at compile-time:

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

Or check it out on DPaste: http://dpaste.1azy.net/7b42daf6

If something is unclear in provided code or you insist on using other approach - please leave a comment here. D has plenty of different tools for compile-time tasks.

Altri suggerimenti

Upon further searching, it turned up http://forum.dlang.org/post/jezkyrguyoshofciuxjq@forum.dlang.org. This is a bug as of DMD 2.061, a workaround is to declare fileNames as alias.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top