TDPL: Overloading template functions
Ryan W Sims
rwsims at gmail.com
Sun Aug 1 20:05:18 PDT 2010
On 7/28/10 7:44 AM, Philippe Sigaud wrote:
> On Wed, Jul 28, 2010 at 05:50, Andrej Mitrovic
> <andrej.mitrovich at gmail.com <mailto:andrej.mitrovich at gmail.com>> wrote:
>
> I won't comment on the double/float issue, I do not anything about it.
>
> T[] find(T, E)(T[] haystack, E needle)
> if (is(typeof(haystack[0] != needle) == bool))
>
> T1[] find(T1, T2)(T1[] longer, T2[] shorter)
> if (is(typeof(longer[0 .. 1] == shorter) : bool))
>
> Also, Andrei, you never explained the if(is()) signature of the
> second templated function. I hope to get some pointers on that. :)
>
>
If I understand the 'is' statement correctly, wouldn't this be a little
less verbose and still the same semantics?
T[] find(T, E)(T[] haystack, E needle)
if (is(typeof(haystack[0] != needle))
{
...do the find...
}
(i.e. just drop the "== bool" from the guard?)
When I compiled it, assert(find([1.0, 2.0], 2) == [2.0]) compiled fine,
and assert(find([1, 2], "2") == []) didn't which is expected. Is there
something I'm missing?
--
rwsims
> I'll have a try at this one.
> As you may know, the is(typeof()) syntax is a way to try to compile an
> expression and see if it works. If it works, it has a type, given by
> typeof and is(Type) returns true. So the first one is really saying:
> "Hey compiler, may I compare an element of haystack (of type T) with an E
> In this case, longer is an array. So longer[0] would be an element, a
> T1. There is no chance that shorter will match as an element cannot be
> equal to an array ... except, of course, if longer is an array of T2[]
> (T1 == T2[]). Longer is a T2[][]. That may happen for arrays of
> strings, strings being arrays of chars. And I think that's the problem
> you have in your last unit test.
>
> Anyway, he takes longer[0..1] to get a slice, which is a dynamic array,
> a T1[] and hence comparable to a T2[]... most of the time.
>
> As for using ': bool' instead of '== bool' as in the first find(), I
> don't think there is any difference in this case. I understand T == U as
> 'T is the exact same type as U', whereas T : U is for me "T is a subtype
> of U". But then, a subtype of bool is pretty much constrained to be a
> bool. The T : U syntax is pretty much only used for classes : if(is(T :
> MyClass)) is saying : 'compile this only if T is a subclass of MyClass'.
>
>
> Philippe
>
>
>
> , except if longer is in fact
More information about the Digitalmars-d
mailing list