simple template constraint - compile error.

WhatMeWorry via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 7 21:19:35 PDT 2015


On Monday, 8 June 2015 at 04:02:26 UTC, WhatMeWorry wrote:
> On Sunday, 7 June 2015 at 23:13:14 UTC, anonymous wrote:
>> On Sunday, 7 June 2015 at 23:08:02 UTC, WhatMeWorry wrote:
>>> However, when I try to add a simple constraint to the 
>>> function like so:
>>>
>>> int arrayByteSize(T)(T[] someArray) if (isDynamicArray(T))
>>
>> You forgot an exclamation mark here. Make that: 
>> isDynamicArray!(T)
>
> Thanks, but I still can't get out of the woods. I've distilled
> everything down to the following:
>
> ------------------------------------------------------------------
>
> int arrayByteSize(T)(T[] someArray)
> {
>     ubyte[] arr = cast(ubyte[]) someArray;
>     return arr.length;
> }
>
> int i = arrayByteSize(dynamicArray);  // works with above 
> function.
>
> ------------------------------------------------------------------
>
> However, if I just add a constraint to the function template
>
> int arrayByteSize(T)(T[] someArray)
>     if (isDynamicArray!(T))
> {
>     ubyte[] arr = cast(ubyte[]) someArray;
>     return arr.length;
> }
>
> int i = arrayByteSize(dynamicArray); // Same call - all hell 
> breaks loose.
>
> Error arrayByteSize(T)(T[] someArray) if (isDynamicArray!T)
> Error: template compilelinkshaders.arrayByteSize cannot deduce 
> function from argument types !()(float[]), candidates are:
>
> Why would a working function call stop working just because a 
> constraint was added to the function?

Oops, I posted before I say Mr. Ruppe's comment.

Also, if you pass int[] to that function, for example, T will
*not* be int[] - it will actually be int.

(T)(T[])

means take an array of T. If you pass int[], it is an array of
int, so that's why T is just int instead of an array.

You probably want to remove that [] from the signature.

------------------------------------------------------------

My code seems to be working fine, or is that just by accident?

float[] dynamicArray = [1.0, 0.0, 1.0];
int i = arrayByteSize(dynamicArray);
myLog!dynamicArray;

dynamicArray = [1, 0, 1]

------------------------------------------------------------

I was trying to draw inspiration from the TDPL with Andrei's 
function
T[] find(T, E) (T[] haystack, E needle)...



More information about the Digitalmars-d-learn mailing list