TDPL: Overloading template functions
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Aug 1 14:15:05 PDT 2010
On Sat, Jul 31, 2010 at 17:24, Andrej Mitrovic
<andrej.mitrovich at gmail.com>wrote:
> I think there really is some bug here. I tried to use your template helper
> function, and it seems the order in which I put two constraints in a
> template signature changes the way dmd compiles the code. Consider this:
>
> T[] find(T, E)(T[] haystack, E needle)
> if (is(typeof(haystack[0] != needle) == bool) &&
> areComparable!(T, E))
>
> ...
> T1[] find(T1, T2)(T1[] longer, T2[] shorter)
> if (is(typeof(longer[0 .. 1] == shorter) : bool) && (areComparable!(T1,
> T2)))
>
> This will give out the error "incompatible types for comparing of string
> and immutable(char)".
>
That's because the first part of the constraint is tested, to allow for
short-circuiting the second part. So the bad array comparison triggers the
problem in object._EqArray.
You should always test for the most general constraint first, I guess. In
this particular case, use areComparable!(A,B) as the first argument to && in
both templates.
> But if I reverse the order of the constraints in the second template, like
> so:
>
> T1[] find(T1, T2)(T1[] longer, T2[] shorter)
> if (areComparable!(T1, T2) && is(typeof(longer[0 .. 1] == shorter) :
> bool))
>
> Then this happily compiles.
>
Well, yes. The second template cannot be instantiated: T1 is a string, T2 is
a character. So isComparable evaluates to 'false' and the constraints
short-circuits to 'false'.
> All of the asserts will call the first templated function.
>
>
Because you are looking for an element in a sequence of element in all three
cases. That's what the first version of find() do.
If you test:
assert(find(d, [1.5]); // [1.5] is a one-element array.
assert(find(d, [1.5, 2.4]); // finding d in d.
assert(find("one two three", "two");
it will activate the second version for all these new asserts: you are
looking for a sequence of elements in a sequence of elements, which is what
the second find does.
Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100801/4c821783/attachment.html>
More information about the Digitalmars-d
mailing list