I'm working on a situation where I'd like to have a certain base class that defines a static associative array and static functions that work with it, and then duplicate this functionality in classes that inherit from it, but with each child class having its own instance of the array. It looks like the child classes just inherit the parent's array, however, rather than creating their own static copy as I was hoping. The following is a super-simplified stripped down version of what I'd hoped to accomplish:
class MyBase {
static string[string] dict;
static void attach(string key, string val) {
dict[key] = val;
}
}
class MySubA : MyBase {
// various unique member variables
}
class MySubB : MyBase {
// ...
}
void main() {
MySubA.attach("a", "a1");
MySubB.attach("b", "b1");
writefln("-:%s", MyBase.dict);
writefln("A:%s", MySubA.dict);
writefln("B:%s", MySubB.dict);
}
Desired output:
-:[]
A:["a":"a1"]
B:["b":"b1"]
Actual output:
-:["a":"a1", "b":"b1"]
A:["a":"a1", "b":"b1"]
B:["a":"a1", "b":"b1"]
Is there a way around this without ditching inheritance and just duplicating the relevant code for each subclass? The actual code for assigning to the array I'm working with is more complex than just the attach function listed above, so I'd like to avoid having to duplicate it each time, or assign to .dict manually, if necessary. I'm wondering if there's a solution involving templates that might work, but I just can't seem to piece it together.