D: Are there function signatures with constraints considered equal if they are of a type directly or parameter names?

Given the function signatures below (and their limitations), will they be considered the same? Both pass my unittests, so I am convinced that they can be, but I would like to know whether they are really identical or whether they are different (but behave the same):

Here, the signature restriction refers to parameter names (I understand that runtime information is not available, my assumption is that the compiler uses them to indicate types of haystacks and needles):

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

Now, if I update to refer to types T and E, it still works. I like this form better because it is obvious that my signature restriction is looking for types (and not runtime information) ... and well this is 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?

+4
source share
2 answers

I personally would use if(is(typeof(T.init != E.init) == bool)) to make sure it is of type vars

(and then when you want T to be a range (and lose array notation, it will be if(isInputRange(T) && is(typeof(T.init.front != E.init) == bool)) )


edit: the best way to test things like extending a test case, for example:

if you take another function:

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

this compiles and works as you expected (prohibition of implementation details ...)

but

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

no (calling binarySearch([1,2,3],0); does not compile on it)

however, as my original answer:

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

it works as expected

+4
source

My first problem is that the signature of the function is not related to static constraints. I think when you use your function, its signature is also generated. Limitations are simply to mismatch and / or generate compile-time errors, but I suppose you cannot talk about the signature of a template function, but perhaps as a signature template :)

In your example, I believe you want to check convertibility from one type to another, say E to T , (this is an int in a double array), which is written using is(E : T) or using the convenient isImplicitlyConvertible template in std.traits.

In the first example, you verify that comparing the values ​​of haystack[0] and needle possible, but there is no way to find 3.14 in an int array, however you can compare int for float, so this static if seems too permissive.

+2
source

All Articles