rocksdb icon indicating copy to clipboard operation
rocksdb copied to clipboard

Add enum_reflection.h & preproc.h

Open rockeet opened this issue 3 years ago • 0 comments

2 years ago, I had created PR #7081 which failed on old MSVC.

Now rocksdb has upgraded to c++17, PR #7081 will not fail in CI, we can continuously migrating existing enum/string conversion code by using this enum refelection.

Below is the brief introduction about enum reflection(copied from PR #7081):


With enum reflection, we can convert enum to/from string

For example:

ROCKSDB_ENUM_PLAIN(CompactionStyle, char,
  kCompactionStyleLevel = 0x0,
  kCompactionStyleUniversal = 0x1,
  kCompactionStyleFIFO = 0x2,
  kCompactionStyleNone = 0x3 // comma(,) can not be present here
);
assert(enum_name(kCompactionStyleUniversal) == "kCompactionStyleUniversal");
assert(enum_name(CompactionStyle(100)).size() == 0);
CompactionStyle cs= kCompactionStyleLevel;
assert(enum_value("kCompactionStyleUniversal", &cs) && cs == kCompactionStyleUniversal);
assert(!enum_value("bad", &cs) && cs == kCompactionStyleUniversal); // cs is not changed

There are 4 macros to define a enum with reflection

// plain old enum defined in a namespace(not in a class/struct)
ROCKSDB_ENUM_PLAIN(EnumType, IntRep, e1 = 1, e2 = 2);
// this generates:
enum EnumType : IntRep { e1 = 1, e2 = 2 };
// enum reflection supporting code ...
// ...
// the supporting code makes template function enum_name and
// enum_value works for this EnumType

// other three macros are similar with some difference:

// enum class defined in a namespace(not in a class/struct)
ROCKSDB_ENUM_CLASS(EnumType, IntRep, Enum values ...);

// plain old enum defined in a class/struct(not in a namespace)
ROCKSDB_ENUM_PLAIN_INCLASS(EnumType, IntRep, Enum values ...);

// enum class defined in a class/struct (not in a a namespace)
ROCKSDB_ENUM_CLASS_INCLASS(EnumType, IntRep, Enum values ...);

rockeet avatar Sep 13 '22 10:09 rockeet