search of a workaround

bearophile bearophileHUGS at lycos.com
Sat Feb 9 04:45:30 PST 2013


monarch_dodra:

> I mean structs you can pack together in an array, eg:
>
> S[10] s10; //10 structs S
>
> You can't do that with classes. Sure, you can put 10 class 
> *references* in an array, but the *instances* themselves need 
> to be individually allocated.

This kind of works, with some limitations (I'll ask to remove one 
limitation):


import std.stdio, std.conv, std.typecons;

class Foo {
     int x;
     this(int x_) { this.x = x_; }
     override string toString() { return text(x); }
}

void main() {
     // scoped!Foo[10] foos;
     typeof(scoped!Foo(1))[10] foos; // Not initialized.

     foreach (i, ref f; foos)
         // f = new Foo(i * 10);
         // f = scoped!Foo(i * 10);
         f.x = i * 10;

     // writeln(foos);
     foreach (ref f; foos)
         writeln(f.x);
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list