Skip to content

4.0 Utility: enumeration

DK edited this page Sep 20, 2023 · 2 revisions

enumeration

On the basis of original stl::enumeration, DKUtil::enumeration adds the following:

  • static reflection for enum value name, type name and class name.
  • std::ranges iterator adaptor for value_range/flag_range.
  • expanded ctor with concept restraint auto templates.

static reflection is not implemented using external lib, DKUtil wraps a lightweight compile time nasty macro inside.

enum class Color : std::uint32_t
{
    red,
    yellow,
    white,
};

// print
Color redColor = Color::red;
INFO("this enum is {}", dku::print_enum(redColor));

// cast
std::string colorStr = "yellow";
auto& colorTbl = dku::static_enum<Color>();
Color yellowColor = colorTbl.from_string(colorStr);

// iterate
for (const Color c : colorTbl.value_range(Color::red, Color::white)) {
    INFO("color is {}", colorTbl.to_string(c));
}

// iterate flag type enum ( 1 << 1, 1 << 2 etc..)
enum class ColorFlag : std::uint32_t
{
    red = 1 << 1,
    yellow = 1 << 2,
    white = 1 << 3,
};
auto& flagTbl = dku::static_enum<ColorFlag>();

for (const ColorFlag c : flagTbl.flag_range(ColorFlag::red, ColorFlag::white)) {
    INFO("color is {}", flagTbl.to_string(c));
}