Search code examples
d

D language: Are function signatures with constraints considered equal if they refer to the type directly or the parameter names?


Given the below function signatures (and their constraints), would they be considered the same? Both pass my unittests, so I am led to believe they may be, but I'd like to know if they are truly identical or if they are different (but behave the same):

Here, the signature constraint refers the parameter names (I realize the runtime information is not available, my assumption is that the compiler uses these to refer to the types of haystack and needle):

T[] find(T, E)(T[] haystack, E needle) 
  if(is(typeof(haystack[0] != needle) == bool)) 
{
  // ...
}

Now, if I update to refer to the types T and E, it still works. I like this form better because it's explicit that my signature constraint is looking the types (and not runtime information)... and well it's more concise:

T[] find(T, E)(T[] haystack, E needle) 
  if(is(typeof(T != E) == bool)) 
{
  // ...
}

Are my assumptions correct or am I missing something?


Solution

  • personally I'd use if(is(typeof(T.init != E.init) == bool)) to ensure it's about the vars of the type

    (and then when you want T to be a range (and losing the array notation it'd be if(isInputRange(T) && is(typeof(T.init.front != E.init) == bool)))


    edit: best way to test things like this is by expanding the test case:

    if we take a different function:

    int binarySearch(T,E)(T[] haystack, E needle)
        if(is(typeof(haystack[0] < needle) == bool)) {
    //...
       return -1;
    }
    

    this compiles and works as you'd expect (barring implementation details...)

    but

    int binarySearch(T,E)(T[] haystack, E needle)
        if(is(typeof(T < E) == bool)) {
    //...
       return -1;
    }
    

    doesn't (calling binarySearch([1,2,3],0); on it doesn't compile)

    however like my original answer:

    int binarySearch(T,E)(T[] haystack, E needle)
       if(is(typeof(T.init > E.init) == bool)) {
        //...
        return -1;
    }
    

    this does work like expected