TDPL: Overloading template functions

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Jul 28 13:44:28 PDT 2010


On page 143 there's a new find() overloaded function which is more
specialized than the last generic function, but I'm still getting an
ambiguity error. Although the book doesn't state if that specific unittest
should work, so I'm left wondering :) Here's the code:

void main()
{
}

T1[] find(T1, T2)(T1[] longer, T2[] shorter)
    if (is(typeof(longer[0 .. 1] == shorter) : bool))
{
    while (longer.length >= shorter.length) {
        if (longer[0 .. shorter.length] == shorter)
            break;
        longer = longer[1 .. $];
    }
    return longer;
}

int[] find(int[] longer, int[] shorter) { }

unittest {
    int[] ints1 = [1, 2, 3, 5, 2] ;
    int[] ints2 = [3, 5];
    auto test = find(ints1, ints2);
}

test.d(16): Error: function test.find conflicts with template
test.find(T1,T2) if (is(typeof(longer[0..1] == shorter) : bool)) at
test.d(5)


And on page 145 the last example is:

void main() { }

void transmogrify(uint) { }
void transmogrify(long) { }
void transmogrify(T)(T value) { }

unittest {
    transmogrify(42);
    transmogrify("hello");
    transmogrify(1.1);
}

test2.d(5): Error: template test2.transmogrify(T) conflicts with function
test2.transmogrify at test2.d(3)

On Wed, Jul 28, 2010 at 7:32 PM, Andrej Mitrovic <andrej.mitrovich at gmail.com
> wrote:

> Woops, I got confused. I was thinking about structs, not arrays.
>
> But yeah, in this case a float gets compared to a double and it seems to
> evaluate to false.
>
>
> On Wed, Jul 28, 2010 at 7:26 PM, Jonathan M Davis <jmdavisprog at gmail.com>wrote:
>
>> On Wednesday, July 28, 2010 09:49:52 Andrej Mitrovic wrote:
>> > IIRC arrays are value types and as such they are compared bit-by-bit
>> > to each other, right?
>>
>> Dynamic arrays are reference types (though static arrays are indeed value
>> types), and they evaluate for equality by comparing each element in turn
>> (though
>> presumably, they compare their length first and don't bother with element
>> comparisons if the lengths don't match). Look at section 4.1.5 on page 100
>> of
>> TDPL.
>>
>> - Jonathan M Davis
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100728/4d8ff15a/attachment.html>


More information about the Digitalmars-d mailing list