Forward references and more

bearophile bearophileHUGS at lycos.com
Mon Oct 12 02:26:58 PDT 2009


What's wrong with this code?

struct MemoryPool(T) {
    alias T[100_000 / T.sizeof] Chunk;
    Chunk*[] chunks;
}
struct Foo {
    int x;
    MemoryPool!(Foo) pool;
}
void main() {}

It prints "Error: struct problem.Foo no size yet for forward reference".
T.sizeof must be 8 in all cases.


So I have tried to pull pool out:

struct MemoryPool(T) {
    alias T[100_000 / T.sizeof] Chunk;
    Chunk*[] chunks;
}
MemoryPool!(Foo) pool;
struct Foo {
    int x;
    // here uses pool
}
void main() {}

But there's a problem still:
Error: struct problem2.Foo no size yet for forward reference

To compile the code I have to move pool forward still:

struct MemoryPool(T) {
    alias T[100_000 / T.sizeof] Chunk;
    Chunk*[] chunks;
}
struct Foo {
    int x;
    // here uses pool
}
MemoryPool!(Foo) pool;
void main() {}

When possible it's better to avoid global variables. To avoid the global variable I may pass the instance pool to Foo. But to do this Foo has to become a struct template. But I am not sure how I can do this.
Do you have any comments or suggestions?

Bye and thank you,
bearophile


More information about the Digitalmars-d-learn mailing list