Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - JB-Lighting/magic_enum: Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code · GitHub
Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JB-Lighting/magic_enum: Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code · GitHub
Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JB-Lighting/magic_enum: Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code · GitHub
Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - JB-Lighting/magic_enum: Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code · GitHub
Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JB-Lighting/magic_enum: Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code · GitHub
Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - JB-Lighting/magic_enum: Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code · GitHub
Skip to content

Repository files navigation

Github releasesConan packageVcpkg packageBuild2 packageMeson wrapLicenseCompiler explorerOpenSSF ScorecardStand With Ukraine

Magic Enum C++

Header-only C++17 library provides static reflection for enums, work with any enum type without any macro or boilerplate code.

If you like this project, please consider donating to one of the funds that help victims of the war in Ukraine: https://u24.gov.ua.

Documentation

  • Basic

    #include<magic_enum/magic_enum.hpp>
    #include<iostream>enumclassColor { RED = -10, BLUE = 0, GREEN = 10 };
    intmain() {
    Color c1 = Color::RED;
    std::cout << magic_enum::enum_name(c1) << std::endl; // REDreturn0;
    }
  • Enum value to string

    Color color = Color::RED;
    auto color_name = magic_enum::enum_name(color);
    // color_name -> "RED"
  • String to enum value

    std::string color_name{"GREEN"};
    auto color = magic_enum::enum_cast<Color>(color_name);
    if (color.has_value()) {
    // color.value() -> Color::GREEN
    }
    // case insensitive enum_castauto color = magic_enum::enum_cast<Color>(value, magic_enum::case_insensitive);
    // enum_cast with BinaryPredicateauto color = magic_enum::enum_cast<Color>(value, [](char lhs, char rhs) { returnstd::tolower(lhs) == std::tolower(rhs); });
    // enum_cast with defaultauto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Integer to enum value

    int color_integer = 0;
    auto color = magic_enum::enum_cast<Color>(color_integer);
    if (color.has_value()) {
    // color.value() -> Color::BLUE
    }
    auto color_or_default = magic_enum::enum_cast<Color>(value).value_or(Color::NONE);
  • Indexed access to enum value

    std::size_t i = 0;
    Color color = magic_enum::enum_value<Color>(i);
    // color -> Color::RED
  • Enum value sequence

    constexprauto colors = magic_enum::enum_values<Color>();
    // colors -> {Color::RED, Color::BLUE, Color::GREEN}// colors[0] -> Color::RED
  • Number of enum elements

    constexpr std::size_t color_count = magic_enum::enum_count<Color>();
    // color_count -> 3
  • Enum value to integer

    Color color = Color::RED;
    auto color_integer = magic_enum::enum_integer(color); // or magic_enum::enum_underlying(color);// color_integer -> -10
  • Enum names sequence

    constexprauto color_names = magic_enum::enum_names<Color>();
    // color_names -> {"RED", "BLUE", "GREEN"}// color_names[0] -> "RED"
  • Enum entries sequence

    constexprauto color_entries = magic_enum::enum_entries<Color>();
    // color_entries -> {{Color::RED, "RED"}, {Color::BLUE, "BLUE"}, {Color::GREEN, "GREEN"}}// color_entries[0].first -> Color::RED// color_entries[0].second -> "RED"
  • Enum fusion for multi-level switch/case statements

    switch (magic_enum::enum_fuse(color, direction).value()) {
    casemagic_enum::enum_fuse(Color::RED, Directions::Up).value(): // ...casemagic_enum::enum_fuse(Color::BLUE, Directions::Down).value(): // ...// ...
    }
  • Enum switch runtime value as constexpr constant

    Color color = Color::RED;
    magic_enum::enum_switch([] (auto val) {
    constexpr Color c_color = val;
    // ...
    }, color);
  • Enum iterate for each enum as constexpr constant

    magic_enum::enum_for_each<Color>([] (auto val) {
    constexpr Color c_color = val;
    // ...
    });
  • Check if enum contains

    magic_enum::enum_contains(Color::GREEN); // -> true
    magic_enum::enum_contains<Color>(2); // -> true
    magic_enum::enum_contains<Color>(123); // -> false
    magic_enum::enum_contains<Color>("GREEN"); // -> true
    magic_enum::enum_contains<Color>("fda"); // -> false
  • Enum index in sequence

    constexprauto color_index = magic_enum::enum_index(Color::BLUE);
    // color_index.value() -> 1// color_index.has_value() -> true
  • Functions for flags

    enum Directions : std::uint64_t {
    Left = 1,
    Down = 2,
    Up = 4,
    Right = 8,
    };
    template <>
    structmagic_enum::customize::enum_range<Directions> {
    staticconstexprbool is_flags = true;
    };
    magic_enum::enum_flags_name(Directions::Up | Directions::Right); // -> "Directions::Up|Directions::Right"magic_enum::enum_flags_name(Directions::Up | Directions::Right, ','); // -> "Directions::Up,Directions::Right"magic_enum::enum_flags_contains(Directions::Up | Directions::Right); // -> truemagic_enum::enum_flags_cast(3); // -> "Directions::Left|Directions::Down"
    magic_enum::enum_flags_cast<Directions>("Left,Down", ','); // -> Directions::Left|Directions::Down
  • Enum type name

    Color color = Color::RED;
    auto type_name = magic_enum::enum_type_name<decltype(color)>();
    // type_name -> "Color"
  • IOstream operator for enum

    using magic_enum::iostream_operators::operator<<; // out-of-the-box ostream operators for enums.
    Color color = Color::BLUE;
    std::cout << color << std::endl; // "BLUE"
    using magic_enum::iostream_operators::operator>>; // out-of-the-box istream operators for enums.
    Color color;
    std::cin >> color;
  • Bitwise operator for enum

    enumclassFlags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
    usingnamespacemagic_enum::bitwise_operators;// out-of-the-box bitwise operators for enums.// Support operators: ~, |, &, ^, |=, &=, ^=.
    Flags flags = Flags::A | Flags::B & ~Flags::C;
  • Checks whether type is an Unscoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_unscoped_enum<color>::value -> true
    magic_enum::is_unscoped_enum<direction>::value -> false
    magic_enum::is_unscoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_unscoped_enum_v<color> -> true
  • Checks whether type is an Scoped enumeration.

    enum color { red, green, blue };
    enumclassdirection { left, right };
    magic_enum::is_scoped_enum<color>::value -> false
    magic_enum::is_scoped_enum<direction>::value -> true
    magic_enum::is_scoped_enum<int>::value -> false// Helper variable template.
    magic_enum::is_scoped_enum_v<direction> -> true
  • Static storage enum variable to string This version is much lighter on the compile times and is not restricted to the enum_range limitation.

    constexpr Color color = Color::BLUE;
    constexprauto color_name = magic_enum::enum_name<color>();
    // color_name -> "BLUE"
  • containers::array array container for enums.

    magic_enum::containers::array<Color, RGB> color_rgb_array {};
    color_rgb_array[Color::RED] = {255, 0, 0};
    color_rgb_array[Color::GREEN] = {0, 255, 0};
    color_rgb_array[Color::BLUE] = {0, 0, 255};
    magic_enum::containers::get<Color::BLUE>(color_rgb_array) // -> RGB{0, 0, 255}
  • containers::bitset bitset container for enums.

    constexpr magic_enum::containers::bitset<Color> color_bitset_red_green {Color::RED|Color::GREEN};
    bool all = color_bitset_red_green.all();
    // all -> false// Color::BLUE is missingbool test = color_bitset_red_green.test(Color::RED);
    // test -> true
  • containers::set set container for enums.

    auto color_set = magic_enum::containers::set<Color>();
    bool empty = color_set.empty();
    // empty -> true
    color_set.insert(Color::GREEN);
    color_set.insert(Color::BLUE);
    color_set.insert(Color::RED);
    std::size_t size = color_set.size();
    // size -> 3
  • Improved UB-free "SFINAE-friendly" underlying_type.

    magic_enum::underlying_type<color>::type -> int// Helper types.
    magic_enum::underlying_type_t<Direction> -> int

Remarks

  • magic_enum does not pretend to be a silver bullet for reflection for enums, it was originally designed for small enum.

  • Before use, read the limitations of functionality.

Integration

  • You should add the required file magic_enum.hpp, and optionally other headers from include dir or release archive. Alternatively, you can build the library with CMake.

  • If you are using vcpkg on your project for external dependencies, then you can use the magic-enum package.

  • If you are using Conan to manage your dependencies, merely add magic_enum/x.y.z to your conan's requires, where x.y.z is the release version you want to use.

  • If you are using Build2 to build and manage your dependencies, add depends: magic_enum ^x.y.z to the manifest file where x.y.z is the release version you want to use. You can then import the target using magic_enum%lib{magic_enum}.

  • Alternatively, you can use something like CPM which is based on CMake's Fetch_Content module.

    CPMAddPackage(
    NAMEmagic_enumGITHUB_REPOSITORYNeargye/magic_enumGIT_TAGvx.y.z# Where `x.y.z` is the release version you want to use.
    )
  • Bazel is also supported, simply add to your WORKSPACE file:

    http_archive(
    name = "magic_enum",
    strip_prefix = "magic_enum-<commit>",
    urls = ["https://github.com/Neargye/magic_enum/archive/<commit>.zip"],
    )
    

    To use bazel inside the repository it's possible to do:

    bazel build //...
    bazel test //...
    bazel run //example
    

    (Note that you must use a supported compiler or specify it with export CC= <compiler>.)

  • If you are using Ros, you can include this package by adding <depend>magic_enum</depend> to your package.xml and include this package in your workspace. In your CMakeLists.txt add the following:

    find_package(magic_enumCONFIGREQUIRED)
    ...target_link_libraries(your_executablemagic_enum::magic_enum)

Compiler compatibility

  • Clang/LLVM >= 5
  • MSVC++ >= 14.11 / Visual Studio >= 2017
  • Xcode >= 10
  • GCC >= 9
  • MinGW >= 9

Licensed under the MIT License

About

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages