magic_enum icon indicating copy to clipboard operation
magic_enum copied to clipboard

Feature request: remove prefix from enum name

Open durka opened this issue 10 months ago • 3 comments

Note: this issue is a reopening of #97.

I'm working with a lot of enums from a C library that look like this:

enum FOO_BAR {
    FOO_BAR_BAZ,
    FOO_BAR_QUUX,
    // etc
};

So when I call enum_name() I get "FOO_BAR_BAZ", or if it's a bitflag I might get "FOO_BAR_BAZ|FOO_BAR_QUUX" etc. But in a lot of cases I already know I'm dealing with a FOO_BAR and this is noise. I would like the strings to omit FOO_BAR_.

Existing solutions to this problem:

  1. Define another enum with the same variants and cast to that one before calling enum_name/enum_flags_name. The issue with this is that the enums are large and in third party generated code so the point of using magic enum is to reduce such chores (I'm replacing old code that is full of const map<FOO_BAR, string>).
  2. Remove the prefix at runtime using enum_name(v).substr(8). This is what I'm doing now and it works but is extra computation. It's also more cumbersome for the flags case where I have to do replace_all(enum_flags_name(f), "FOO_BAR_", "").

My desired solution:

A boolean or other setting in the customize struct that makes magic_enum do this for me automagically.

template <>
struct magic_enum::customize::enum_range<FOO_BAR> {
    // one possibility, assuming the prefix is always the name of the enum plus an underscore
    constexpr bool remove_name_prefix = true;

    // more flexible but maybe harder to implement?
    constexpr char* prefix = "FOO_BAR_";

    // another idea
    constexpr int prefix_len = 8;
};

There could also be a flag to pass to enum_[flags_]name to override the setting and keep the prefix.

durka avatar Feb 20 '25 18:02 durka

Hi durka, is this still needed? if so I will make a pr for it

ZXShady avatar Jun 09 '25 23:06 ZXShady

I would definitely find it useful!

On Mon, Jun 9, 2025, 7:38 PM ZXShady @.***> wrote:

ZXShady left a comment (Neargye/magic_enum#402) https://github.com/Neargye/magic_enum/issues/402#issuecomment-2957292514

Hi durka, is this still needed? if so I will make a pr for it

— Reply to this email directly, view it on GitHub https://github.com/Neargye/magic_enum/issues/402#issuecomment-2957292514, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAALPH4VTHS54Z4FRVZ5HKT3CYLGHAVCNFSM6AAAAABXRPXEYGVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDSNJXGI4TENJRGQ . You are receiving this because you were mentioned.Message ID: @.***>

durka avatar Jun 10 '25 00:06 durka