Type inference and overloaded functions

Namespace rswhite4 at googlemail.com
Wed Dec 11 11:35:20 PST 2013


On Wednesday, 11 December 2013 at 18:31:20 UTC, Namespace wrote:
> On Wednesday, 11 December 2013 at 16:28:39 UTC, Chris Cain 
> wrote:
>> On Wednesday, 11 December 2013 at 09:49:13 UTC, Namespace 
>> wrote:
>>> On Wednesday, 11 December 2013 at 04:01:11 UTC, Ali Çehreli 
>>> wrote:
>>>> On 12/10/2013 04:37 PM, Namespace wrote:
>>>>
>>>> >   int[] arr2 = [7, 8, 9]s;
>>>> >   assert(is(typeof(arr2) == int[3]));
>>>>
>>>> That looks very confusing. The left-hand side looks like a 
>>>> slice, which I can append elements to but its type is a 
>>>> static array?
>>>>
>>>> Ali
>>>
>>> That is intended (but can be discussed of course). It was 
>>> often desired to write int[$] arr = [1, 2, 3]; to 
>>> auto-determine the dimension. And my change does something 
>>> like that: if you assign a static array to a slice, the 
>>> dimension is auto-determined and the type is adapted.
>>
>> I agree with Ali. arr2 says it's a dynamic array but it's not. 
>> This could easily lead to errors worse than the class caused 
>> by implicit conversions (what's worse than explicitly saying 
>> you want an x but getting a y instead?). `int[$]` for this 
>> purpose would be acceptable, however. I actually like that 
>> idea, personally.
>
> Ok, I will change that. ;)
> And I will try to implement the syntax for int[$].

Was a bit tricky but it works now (even if it may not be perfect):
https://github.com/Dgame/dmd/commits/static_array_literals

Example:

----
import std.stdio;

void foo(int[3] arr) {
	assert(is(typeof(arr) == int[3]));
}

void bar(T)(T arr) {
	assert(is(T == int[3]));
}

void quatz(int[] arr) {
	assert(is(typeof(arr) == int[]));
}

void main() {
	int[] arr0 = [1, 2, 3];
	assert(is(typeof(arr0) == int[]));
	assert(arr0 == [1, 2, 3]);

	int[3] arr1 = [4, 5, 6]s;
	assert(is(typeof(arr1) == int[3]));
	assert(arr1 == [4, 5, 6]);

	int[] arr2 = [7, 8, 9]s;
	assert(is(typeof(arr2) == int[/*3*/]));
	assert(arr2 == [7, 8, 9]);

	int[$] arr_a1 = [54, 74, 90, 2010];
	assert(is(typeof(arr_a1) == int[4]));
	assert(arr_a1 == [54, 74, 90, 2010]);

	int[$] arr_a2 = [2010, 90, 74, 54]s;
	assert(is(typeof(arr_a2) == int[4]));
	assert(arr_a2 == [2010, 90, 74, 54]);

	foo([1, 2, 3]);
	foo([4, 5, 6]s);

	bar([44, 55, 66]s);

	auto arr3 = [111, 222, 333];
	assert(is(typeof(arr3) == int[]));

	auto arr4 = [444, 555, 666]s;
	assert(is(typeof(arr4) == int[3]));

	quatz([3, 2, 1]);
	quatz([8, 7, 6]s);
}
----


More information about the Digitalmars-d-learn mailing list