Provide cute and powerful enum reflection for C/C++ enum.
- Enum reflection is generated by cute enum compiler(short for CEC).
- The generated code is just a single head file.
- It is just a simple class.
- It can be embeded into other class.
- It supports C++11 standard(But it can be up to you to decide).
- It has no third party dependencies.
- It has no C++ template.
- It has no C macro(except a head file include guard).
- It is tiny code(the example < 70 lines, and fixed API code < 60 lines).
- It is clean and human readable code.
- It supports GCC/MSVC/Clang/MinGW/...all well known C/C++ compiler.
- It is better code(test pass with clang-tidy and unit test code).
- It is more safe code(with compile time check, the value range won't overflow).
- The unit test code can also be automatically generated for you.
- Change coding style for the code is a easy job.
- Add or remove API for the code is a easy job too.
Given a enum Color.txt.
enum class Color:char{
Red,
Green,
Blue
};
Run command "cec Color.txt --output Color.hpp", it will generate Color.hpp, which can be used and tested like this:
#include "Color.hpp" // Test target.
#include <iostream> // for test console io
#include <string> // for test compare string
#include <cassert> // for test assert
#define assert_true(x) assert(x)
int main()
{
// Create enum.
Color c1 = Color::Blue;
assert_true(c1 == Color::Blue);
// Convert enum to string.
assert_true(std::string("Blue") == Color::_toString(c1));
// Convert string to enum.
Color c2 = Color::_fromString("Red");
Color c3 = Color::Red;
assert_true(Color::_good(c2));
assert_true(Color::_good(c3));
assert_true(c2 == c3);
// Convert string to enum, a bad example
Color c4 = Color::_fromString("a bad string");
assert_true(std::string("") == Color::_toString(c4));
assert_true(Color::_good(c4) == false);
// Iterate.
for (auto ev = Color::_min(); ev <= Color::_max(); ++ev){
std::cout << std::to_string(ev);
std::cout << " ==> ";
std::cout << Color::_toString(Color(ev));
std::cout << std::endl;
}
// Iterate all keys.
for (auto i = 0; i < Color::_size(); i++){
std::cout << "key[" << i << "] = " << Color::_keyTable()[i] << std::endl;
}
// Size check.
Color c = Color::Blue;
assert_true(sizeof(c) == sizeof(Color));
assert_true(sizeof(c) == sizeof(char));
assert_true(sizeof(c) == sizeof(Color::_min()));
assert_true(sizeof(c) == sizeof(Color::_max()));
// Switch-case.
Color c5 = Color::Green;
switch (c5){
case Color::Red: { assert_true(0); break; }
case Color::Green: { assert_true(1); break; }
case Color::Blue: { assert_true(0); break; }
default: { assert_true(0); }
}
// Others.
assert_true(Color::_size() == 3);
assert_true(std::string("Color") == Color::_name());
assert_true(std::string("char") == Color::_type());
std::cout << "--done--" << std::endl;
return 0;
}
https://github.com/aantron/better-enums
https://github.com/Neargye/magic_enum
https://en.cppreference.com/w/cpp/language/enum
https://github.com/skvadrik/re2c
https://eel.is/c++draft/