On Saturday, 3 January 2015 at 15:00:53 UTC, Ondra wrote:


I'm not sure if there's a way around that other than to add some code in the class to register itself. You could use a static constructor that adds itself to a list.

Or, to give each class a shared ID, you could add a static member which returns some variation of its typeinfo. In fact, typeid(any_class) returns a unique identifier for each class (an instance of TypeInfo), maybe you can use it directly.

Hi Adam,

static this is probably way to go, I wanted to avoid this solution because if it leads to copy-pasting code to every child.

I need to have IDs small like 8bits, co I probably can't use typeid...

Thank you for answer. Knowing that someting cannot be done is better than spend on this another few hour.

Great book btw.

Ondra

Hello, here is another solution: a class ID is generated lazily, when queried
It does not recquire a static constructor.

----
module runnable;

static string[] IDs;

ptrdiff_t getClassID(ClassType)() if (is(ClassType == class))
{
    import std.algorithm;
    auto classTypeString = ClassType.stringof;
    ptrdiff_t result = countUntil(IDs, classTypeString);
    if (result == -1) {
        IDs ~= classTypeString;
        result = IDs.length -1;
    }
    return result;
}

void main(string[] args)
{
    class A{}
    class B{}
    class C{}
    class D{}

    assert(getClassID!A == 0);
    assert(getClassID!B == 1);
    assert(getClassID!C == 2);
    assert(getClassID!D == 3);
    assert(getClassID!C == 2);
    assert(getClassID!B == 1);
    assert(getClassID!A == 0);
}
----

Hoping it matches to your needs.

Reply via email to