template type deduction of static 2d arrays

uri via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 24 16:46:27 PDT 2014


On Friday, 24 October 2014 at 23:20:02 UTC, ketmar via 
Digitalmars-d-learn wrote:
> On Fri, 24 Oct 2014 22:32:57 +0000
> uri via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> 
> wrote:
>
>> Hi All,
>> 
>> I was wondering why in the code below f1() works but f2 
>> template version called in the same manner does not. Is there 
>> a good reason from a language/compiler perspective?
>> 
>> Thanks.
>> uri
>> 
>> 
>> ---
>> auto f1(int[2][2] m)
>> {
>>      return m[0][0]*m[1][1]-m[0][1]*m[1][0];
>> }
>> auto f2(T)(T[2][2] m)
>> {
>>      return m[0][0]*m[1][1]-m[0][1]*m[1][0];
>> }
>> 
>> void main()
>> {
>>      auto res = f1( [[1,2],[3,4]]); // works
>>      assert(res == -2);
>> 
>>      res = f2([[1,2],[3,4]]); // deos not work
>> }
>> 
>> Calling f2() as done above gives the following error:
>> 
>> Error: cannot deduce function from argument types 
>> !()(int[][]), candidates are:
>> f2(T)(T[2][2] m)
> by the way, this will work too:
>
>   int[2][2] v = [[1,2],[3,4]];
>   res = f2(v);
>
> 'cause 'v' has correct type, and initializing 'v' does 'magic 
> casting'.

Thanks for replying.

I think it should work because there's no ambiguity. I now have 
to uglify my code and make it !@safe or create a temporary.

I also noticed this when trying things out:

auto f2(T)(int[2][2] m) // Same error as above
auto f2()(int[2][2] m) // Works as per non-template function


On a related note, does the D spec guarantee the following will 
be rectangular in memory?

auto a = [ [1,2],[3,4] ];


Cheers,
uri




More information about the Digitalmars-d-learn mailing list