Array of structs construction
Era Scarecrow
rtcvb32 at yahoo.com
Fri Oct 19 20:49:13 PDT 2012
On Saturday, 20 October 2012 at 01:06:57 UTC, bearophile wrote:
> I'd like to write code like this (the constructors of the
> structs must take 1 argument):
>
> // some imports here
> void main() {
> BigInt[] data1 = [5, 6, 9];
> Ranged!(int,5,10)[] data2 = [5, 6, 9];
> Nibble[] data3 = [1, 2, 15]; // Nibble.sizeof == 1
> alias Typedef!int Mint;
> Mint[] data4 = [5, 6, 9];
> }
>
>
> Do you like this feature?
>
> Currently in D you write this, it's not handy if you have many
> items:
>
> // some imports here
> void main() {
> auto data1 = [BigInt(5), BigInt(6), BigInt(9)];
> alias Ranged!(int,5,10) R; // a short name
> auto data2 = [R(5), R(6), R(9)];
> auto data3 = [Nibble(1), Nibble(2), Nibble(15)];
> alias Typedef!int Mint;
> Mint[] data4 = [Mint(5), Mint(6), Mint(9)];
> }
Only way i can see this working simply, is if it's auto, at
least one of the items have to specify it's full type and the
rest can be ignored. Also it must have a constructor that takes
that one type of argument. So..
//50 & 100 aren't BigInt, but can be constructed to be one..
auto bignums = [BigInt(25), 50, 100];
As for above arrays where the type is known, I can't see a
reason why it can't work.
In a large array of static data I've had to make shortcut names
for several structs in order to keep it readable and
programmable. This may help in some cases, or perhaps all of them.
Course this also means if a structure is being initialized then
perhaps it can be extended. Like the above, except...
struct S {
int x,y;
BigInt z;
}
S s = {1,2,3}; //3 converted if BigInt has a constructor for int
//if that's illegal, then you'd do this to make it work instead,
//which seems... unnecessary.
struct S {
int x,y;
BigInt[1] z;
}
S s = {1,2,[3]};
The downside is if there's memory allocation or heavy work that
can't be done at compile-time then there may be more complex
issues trying to optimize something. Makes it sorta mixed.
More information about the Digitalmars-d
mailing list