Showing posts with label cpp_enum. Show all posts
Showing posts with label cpp_enum. Show all posts

Nov 21, 2025

[C++] untyped enum value range

Enumerations: dcl.enum#8

[dcl.enum]

"For an enumeration whose underlying type is not fixed, the values of the enumeration are the values of the underlying type in the range b{min} to b{max}, where b{min} and b{max} are, respectively, the smallest and largest values of the smallest bit-field that can store the values of the enumerators."


How the Range is Calculated

The standard uses a "smallest bit-field" logic (powers of two) to determine valid values:
Find the Min/Max labels: Let e{min} be the smallest enumerator and e{max} be the largest.

  • Determine the Range:If e{min} >= 0
    • The range is [0, 2^k - 1], where 2^k is the smallest power of two such that e{max} < 2^k.
  • If e{min} < 0
    • The range includes negative numbers, typically corresponding to a signed bit-field (two's complement). The range is [-2^k, 2^k - 1].


Oct 4, 2016

[c++] [cppcon2016] Constant fun

enum  bm { b0 = 0x1, b1 = 0x2, b2 = 0x4 };
int b = bm::b0 | bm::b1;

//---
enum  bm { b0 = 0x1, b1 = 0x2, b2 = 0x4 };
bm b = bm::b0 | bm::b1; // bad conversion

//--
enum  bm { b0 = 0x1, b1 = 0x2, b2 = 0x4 };

bm b = bm(bm::b0 | bm::b1); //OK

//--
enum class bm { b0 = 0x1, b1 = 0x2, b2 = 0x4 };
bm b = bm(bm::b0 | bm::b1); // no such op!!

//--
enum class bm { b0 = 0x1, b1 = 0x2, b2 = 0x4 };

constexpr bm operator| (bm v0, bm v1) {
return bm(int(v0) | int(v1));
}

bm b = bm::b0 | bm::b1;

switch (b) {
case bm::b0 | bm::b1: /*...*/; // OK due to constexpr operator
}

//--


Aug 20, 2015

[C++][Enum Macro]

from reddit:
----------
#define STRONG_ENUM(Name, ...) \
    class Name { \
    public: \
        enum Name##_ { \
            __VA_ARGS__ \
        }; \
    public: \
        Name(Name::Name##_ v) : mValue(v) {} \
        operator Name::Name##_() const { return mValue; } \
        Name& operator=(Name::Name##_ v) { \
            mValue = v; \
            return *this; \
        } \
    private: \
        Name::Name##_ mValue; \
    }

usage:
STRONG_ENUM(Color,
    Red,
    Green,
    Blue
);

const char* tostring(Color c) {
    switch(c) {
    case Color::Red:
        return "red";
    case Color::Green:
        return "green";
    case Color::Blue:
        return "blue";
    }
}

Color c = Color::Red;
std::cout << tostring(c) << std::endl;