T[] (array of generic type)

Jon no at spam.com
Mon Nov 18 12:56:49 PST 2013


On Monday, 18 November 2013 at 20:45:54 UTC, seany wrote:
> On Monday, 18 November 2013 at 20:42:36 UTC, Jon wrote:
>> On Monday, 18 November 2013 at 20:20:38 UTC, seany wrote:
>>> I read that book, but dont find this constructtion, that is 
>>> why the question.
>>
>> Seany, you are on the right track for the function 
>> declaration, I think the following code does what you are 
>> looking for:
>>
>> import std.stdio;
>>
>> void main() {
>> 	int[4] myArray;
>> 	assign(myArray, 5);
>> 	writeln(myArray);              //prints [5, 5, 5, 5]
>> }
>>
>> void assign(T)(T[] arr, T val)
>> {
>> 	for(int i = 0; i < arr.length; i++)
>> 	{
>> 		arr[i] = val;
>> 	}
>> }
>>
>> D is great because the template system infers what type you 
>> are passing without having to explicitly instantiate the 
>> template first, i.e. assign!(int)(myArray, 5).
>
>
> thank you, precisely this is what i was looking for, any 
> peculiar pitfalls to be aware of?

With this particular usage, it should work the way you expect. 
Things can get a little hairy when you are trying to do more 
complicated compile-time checking and things like that. 
Philippe's guide and the D Language Reference should get you 
through 99% of any issues you face, but sometimes it takes a lot 
of trial and error!

-Jon



More information about the Digitalmars-d-learn mailing list