Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: remove prefix from enum name #402

Open
durka opened this issue Feb 20, 2025 · 0 comments
Open

Feature request: remove prefix from enum name #402

durka opened this issue Feb 20, 2025 · 0 comments
Milestone

Comments

@durka
Copy link

durka commented Feb 20, 2025

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.

@Neargye Neargye added this to the v0.9.8 milestone Feb 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants