Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare class member at runtime in D

I want the following struct as a class member, but I don't know the type of T, so I need "declare" the struct at runtime.


struct Chunk (T) {
    string id;
    T[][] data;
}

class FileBla {
    this() {
        Chunk !int ck; // need to be turned in a class member
    }
}

Should be missing something easy.

like image 753
Pedro Lacerda Avatar asked Jun 07 '26 22:06

Pedro Lacerda


2 Answers

You can template the class as well:

import std.stdio;

struct Chunk (T) {
    string id;
    T[][] data;
}

class FileBla(T) {
private:
    Chunk!T ck;
}

void main() {
    auto f = new FileBla!int;
    writeln(typeid(f.ck));
}
like image 62
van Avatar answered Jun 10 '26 21:06

van


I'll assume you're used to programming in dynamic languages and are now trying to learn a static language.

There are at least three reasonable ways to do this:

Template FileBla, too:

class FileBla(T) {
    Chunk!T ck;

    // Other stuff.
}

Wrap Chunk in a polymorphic class.

Allocate Chunk on the heap and store a void* pointer to it. This is the old C-style way to do things, will require manually casting the pointer to the correct type, and is not memory safe. Nonetheless it is occasionally useful.

like image 24
dsimcha Avatar answered Jun 10 '26 21:06

dsimcha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!