jeudi 21 juin 2018

C++ Reflection for bit field structs

I am looking for a way to do "reflection" in C++ over a bit-field struct like this:

 struct Bits {
    uint32_t opCode : 5;
    uint32_t header : 3;
    uint32_t source : 5;
    uint32_t destination : 5;
    uint32_t offset : 13;
 };

My goal is to be able to get things like:

  1. All member names as std::string list ex. "opCode", "header", etc...
  2. The underlying typename as a std::string ex. "uint32_t"
  3. The number of bits for each field as a std::int list ex. 5,3,5,5,13

with minimal hand-coding, macros, or boilerplate code.

After reading through this StackOverflow post, it is clear there are some "reflection" capabilities provided by libraries outside of standard C++. Looking into things like Precise and Flat Reflection, Ponder, Boost Reflect, and even Boost Hana, I have not found support for something like this.

I have already found a way to get the member names and typenames of a non-bitfield struct using Boost Hana [this achieves #1 and #2 for ordinary structs], and there is a way to get the member names of a bitfield struct using Boost Fusion [this achieves #1 for bitfield structs], though it is messy.

Alternatively, manually flattening/decaying the struct to a single unit32_t member struct like:

struct BitsFlattened{
  uint32_t message;
}

with manually coded getters and setters for the appropriate members is also a possibility, where getters might expose the information by their name ex. getopCode05(), getheader69().





Aucun commentaire:

Enregistrer un commentaire