Search code examples
templatesoverloadingd

Where's the conflict here?


Why can't I overload this template function?

import std.stdio;

T[] find(T, E)(T[] haystack, E needle)
    if (is(typeof(haystack[0] != needle)))
{
    while(haystack.length > 0 && haystack[0] != needle) {
        haystack = haystack[1 .. $];
    }
    return haystack;
}

// main.d(14): Error: function main.find conflicts with template main.find(T,E) if (is(typeof(haystack[0] != needle))) at main.d(5)
double[] find(double[] haystack, string needle) { return haystack; }

int main(string[] argv)
{
    double[] a = [1,2.0,3];
    writeln(find(a, 2.0));
    writeln(find(a, "2"));
    return 0;
}

As far as I can tell, the two functions can't accept the same argument types.


Solution

  • You can't overload template functions with non-template functions due to a bug. This should hopefully be fixed sometime in the future.

    In the meantime, you can write the other function as a template specialisation:

    T find(T : double[], E : string)(T haystack, E needle)
    {
        return haystack;
    }