An associative array, where is the TypeInfo class the key in D?

I would like to be able to create a multimodal associative array where one dimension is a class. Like this:

class Node{
    Node[?classType?][string] inputs;
}

so that later I can

Node[] getInputsOfType(?? aClass){
   if(aClass in this.inputs)
      return this.inputs[aClass];
   else
      return null;
}

// meanwhile in another file...

Node[] effects = someAudioNode.getInputsOfType(AudioEffect);

I just got lost. Any ideas?
As for the last part: can a class be used as a parameter in itself? ( AudioEffectin this example, a class.)

BR

[update / permission]

Thanks for answers)!

I thought it would be nice to post the result. Ok, I searched .classinfoin the source code and found that it returns an instance of TypeInfo_Class and that there is .name-property, a string. So this is what I came up with:

#!/usr/bin/env dmd -run
import  std.stdio;
class A{
    int id;
    static int newId;
    A[string][string] list;
    this(){ id = newId++; }
    void add(A a, string name){
        writefln("Adding: [%s][%s]", a.classinfo.name, name);
        list[a.classinfo.name][name] = a;
    }
    T[string] getAllOf(T)(){
        return cast(T[string]) list[T.classinfo.name];
    }
}
class B : A{ }
void main(){
    auto a = new A();
    a.add(new A(), "test");
    a.add(new B(), "bclass");
    a.add(new B(), "bclass2");

    auto myAList = a.getAllOf!(A);
    foreach(key, item; myAList)
        writefln("k: %s, i: %s id: %s",
                key, item.toString(), item.id);

    auto myBList = a.getAllOf!(B);
    foreach(key, item; myBList)
        writefln("k: %s, i: %s id: %s",
                key, item.toString(), item.id);
}

It outputs:

Adding: [classtype.A][test]
Adding: [classtype.B][bclass]
Adding: [classtype.B][bclass2]
Trying to get [classtype.A]
k: test, i: classtype.A id: 1
Trying to get [classtype.B]
k: bclass2, i: classtype.B id: 3
k: bclass, i: classtype.B id: 2

So, I think it works. Yey Anyone have any ideas for improvement?

Are there any pitfalls here?

  • classinfo.name ?
  • "" ?

, ? , classtype.. , , , SO-. !

BR

+3
1

ClassInfo ( .classinfo), . ClassInfo , (. D AAs / ). , , ClassInfo, AA. , , ClassInfo, ClassInfo .


,

if (key in aa)
    return aa[key];
else
    return null;

auto pvalue = key in aa;
return pvalue ? *pvalue : null;
+3

Source: https://habr.com/ru/post/1752722/


All Articles