Shortest way to allocate an array and initialize it with a specific value.

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 11 07:24:36 PDT 2015


On 6/11/15 7:51 AM, Daniel Kozák via Digitalmars-d-learn wrote:
>
> On Thu, 11 Jun 2015 11:43:25 +0000
> via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
>
>> On Thursday, 11 June 2015 at 08:33:46 UTC, Daniel Kozák wrote:
>>> On Wed, 10 Jun 2015 20:22:17 +0000
>>> Adel Mamin via Digitalmars-d-learn
>>> <digitalmars-d-learn at puremagic.com>
>>> wrote:
>>>
>>>> ubyte[5] a = 0xAA; // Fine. Five 0xAA bytes.
>>>> auto a2 = new ubyte[5]; // Fine. Five 0 bytes.
>>>> Now, let's say, I want to allocate an array of a size, derived
>>>> at run time, and initialize it to some non-zero value at the
>>>> same time. What would be the shortest way of doing it?
>>>
>>> import std.stdio;
>>>
>>> struct Ubyte(ubyte defval) {
>>>      ubyte v = defval;
>>>      alias v this;
>>> }
>>>
>>> void main() {
>>> 	auto a2 = new Ubyte!(0xAA)[5];
>>> 	writeln(a2);
>>> }
>>
>> I like this one :-)
>
> small enhancment:
> struct Ubyte(ubyte defval = 0)

import std.typecons;

alias Ubyte(ubyte defval = 0) = Typedef!(ubyte, defval);

I personally like the range solution the best, it has the most flexibility.

-Steve


More information about the Digitalmars-d-learn mailing list