mirror of
https://github.com/aantron/better-enums.git
synced 2025-12-06 16:56:42 +08:00
4.6 KiB
4.6 KiB
Better Enums is a single header file that causes your compiler to generate reflective enum types. This makes it easy to translate between enums and strings, and much more.
Here's how to use a Better Enum:
enabledeclare
parse print
count iterate
switch
safe cast
at compile time
#include <enum.h>
ENUM(Channel, int, Red = 1, Green, Blue)
Channel c = Channel::_from_string("Red");
const char *s = c._to_string();
size_t n = Channel::_size;
for (Channel c : Channel::_values())
run_some_function(c);
switch (c) {
case Channel::Red: // ...
case Channel::Green: // ...
case Channel::Blue: // ...
}
Channel c = Channel::_from_integral(3);
constexpr Channel c = Channel::_from_string("Blue");
What do you get?
- Uniform interface for $cxx98 and $cxx11 Scoped, sized, reflective enums for $cxx98.
-
Compile-time reflection
Have the compiler do additional enum processing using your own
templates or
constexprfunctions. - Non-contiguous sequences Iteration and count much easier to maintain than with an extra "count" constant and making assumptions.
-
Plays nice with
switchUse a Better Enum like a built-inenum, and still have the compiler do case checking. -
Unobtrusive syntax
No ugly macros. Use initializers just like with built-in
enums. Generated members have underscores to avoid conflicts with your constant names. -
Don't repeat yourself
No more unmaintanable maps or
switchstatements for converting enums to strings. -
No build-time generator needed
Just include
enum.h. It's a metaprogram executed by your compiler. -
Fast compilation
Much less impact on build time than even just including
iostream. -
No external dependencies
Uses standard $cxx and supported on major compilers. Installation is
simple — just download
enum.h. - Free and open source Released under the BSD license for use in any project, free or commercial.
It's what built-in enums ought to do.
The library notionally extends $cxx, adding oft-needed features.
-
Download
enum.hCurrent version: $version
To install, just add the file to your project. - Visit on GitHub Follow development, report issues, and let me know if you find this library useful!
Resources
%% title = Clean reflective enums for C++
%% description = Reflective enums for C++ with clean syntax, in a header-only library. Can be converted to strings, iterated, counted, and used for metaprogramming. Free under the BSD license.
%% class = index