On Saturday, 21 August 2021 at 17:33:51 UTC, Jeremy T. Gibson wrote:
is there a simple way to get the unqualified name of a class at runtime without having to pass it through std.format? `typeid(class).name` always yields the full classname, including its module information (i.e., "modulename.classname"), where I only want "classname" on its own.

https://dlang.org/phobos/object.html#.TypeInfo_Class.name is all you have there, and it's just a string, so the simple way is to manipulate the string.

This seems a bit silly but I'm not worried about VMS 2.0 coming along and changing how extensions work ("nodot".extension == "" however, so if module-less classes are possible then this would fail with a RangeError):

```d
class Whoami {
    string report() {
        import std.path : extension;

        return "class: " ~ typeid(this).name.extension[1..$];
    }
}

class AnotherOne : Whoami {}

unittest {
    assert((new Whoami).report == "class: Whoami");
    assert((new AnotherOne).report == "class: AnotherOne");
}

string unqualified(string name) {
    import std.string : lastIndexOf;
    import std.algorithm : min;

    const i = name.lastIndexOf('.');
    return i == -1 ? name : name[min(i+1, $) .. $];
}

unittest {
    assert(typeid(new Whoami).name.unqualified == "Whoami");
assert(typeid(new AnotherOne).name.unqualified == "AnotherOne");
    assert("".unqualified == "");
    assert("x".unqualified == "x");
    assert("x.".unqualified == "");
}
```

Reply via email to