Skip to content

FR: Possible Integration of magic_enum #610

@stellarpower

Description

@stellarpower
  • Compiler Used: clang-15
  • Operating System: Ubuntu 22.04
  • Architecture (ARM/x86/32bit/64bit/etc): AMD64

This is a snippet to add enums automagically:

template<typename Enumeration> void addEnum(ModulePtr m){

   
    constexpr string_view    TypeName = magic_enum::enum_type_name<Enumeration>();
    constexpr size_t       EntryCount = magic_enum::enum_count    <Enumeration>();

    constexpr array<  pair<Enumeration, string_view>, EntryCount  > Entries = magic_enum::enum_entries<Enumeration>();
    
    vector<pair<Enumeration, string>> runtimeEntries;
    runtimeEntries.reserve(EntryCount);

    for (const auto &[value, name] : Entries)
        runtimeEntries.push_back( pair<Enumeration, string>(value, name) );

    utility::add_class<Enumeration>(
        *m,
        string(TypeName),
        runtimeEntries
    );
    
}

Am dropping here as hope it is of some use to someone.

Ideally the utility from !233 could be patched to be more generified not to need specifically a vector of values and strings, but instead, an iterable range of values and string-like objects. This would allow passing in the output from magic_enum::enum_entries<Enumeration>() directly. As it stands we could also probably use ranges rather than the explicit for loop.

Should not take too long to implement, but don;t have a time to open a branch today.

Also not sure if we should get conversion to the underlying integer for free. Am not seeing it right now but maybe I am overlooking something.

It looks like the develop branch is now requiring C++17 support, in which case it's be possible to integrate magic_enum into Chaiscript to automate this. Although C++23 should be bringing some sort of reflection capabilities, so would understand a motivation to hold off and see what comes of that, as without needing nearly as much boilerplate this would make Chaiscript really awesome!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions