开发者

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.


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));
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜