Thread overview
Doing a `static foreach` or `foreach` through enum members in a template or CTFE function, while disabling deprecation warnings
April 19

I know that DStep generates CTFE functions to automatically make aliases for enum members so that the can be used without the enum name, as is done in C. DStep does it with a CTFE function, though it should also be possible with a mixin template.

Here is my attempt so far, using a mixin template:

template enumMixin(Enum) {
    private import std.traits;
    static foreach(member; EnumMembers!Enum) static if (__traits(isDeprecated, member))
    {
        private alias m = __traits(identifier, member);
        alias m = member;
    }
};

It hasn't worked so far.

April 19

Well, someone on the Discord server has been helping me attempt this, but while I managed to get a solution that compiles without errors, I still get the deprecation warning.

Here is what I ended up with:

template enumMixin(alias Enum) {
    static foreach(m; __traits(allMembers, Enum)) static if (!__traits(isDeprecated, __traits(getMember, Enum, m)))
    {
        mixin("alias "~m~" = __traits(getMember, Enum, m);");
    }
};

Unfortunately, the deprecation warnings still appear if the enum contains any deprecated members. I'm starting to suspect that the language doesn't currently have any features to stop this from happening. This is unfortunate, as it should be possible to process an enum with deprecated members without getting these warnings.

April 19

On Friday, 19 April 2024 at 22:24:17 UTC, Liam McGillivray wrote:

>
template enumMixin(alias Enum) {
    static foreach(m; __traits(allMembers, Enum)) static if (!__traits(isDeprecated, __traits(getMember, Enum, m)))
    {
        mixin("alias "~m~" = __traits(getMember, Enum, m);");
    }
};

Correction: The code shown above actually does work properly without any deprecation warnings. I made a mistake with the enum being set to the CTFE function I was previously using instead of this template. This template actually works.

I posted here for visibility and searchability, in case anyone else wants to do something like this.