Search code examples
d

Why does function template work with int[] but not with char[] arrays in D?


Let's say we have a simple D function template that returns the length of an array:

size_t len(T)(T[] arr) {
    return arr.length;
}

And we have two arrays:

int[] arr0 = [1, 1, 2, 3, 5, 8];
char[] arr1 = ['a', 'b', 'c', 'd', 'e'];

Now, I also need a function template that will pretty-print the input and the result of the above len function template.

void writeResult(T)(T[] param, T result) {
    import std.stdio;
    import std.format;
    writeln(format("%s --> %s", param, result));
}

Now let's test len with our two arrays.

writeResult(arr0, len(arr0)); // [1, 1, 2, 3, 5, 8] --> 6
writeResult(arr1, len(arr1)); // writeResult cannot deduce function from argument types !()(char[], uint), candidates are:
test.d(4): writeResult(T)(T[] param, T result)

We have return type size_t for both cases but with int[] array it works and with char[] array it doesn't. What is the reason for such behavior?


Solution

  • The thing to notice there are the arguments to your function are both of basically the same type: T[] and T.

    Replace the T placeholder across the whole signature: int[], int works for your array and length... but with char, char[], char, now you have the problem: len returns size_t (aka uint on 32 bit which is why you see that in the error message), which is not the same as char.

    I'd probably just make the second parameter size_t directly instead of T, or pass some other thing to it.

    Just remember those placeholders in the function definition are always going to be the same every time they are mentioned in a particular call.