0

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. These values should in principal, be able to be determined at compile-time, though it is not a necessity.

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 a custom code solution.

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

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().

Ð..
  • 298
  • 5
  • 18
  • I am ok with using open-source libraries, metaprogramming, Boost, etc. I guess I shouldn't write "native C++". Sorry for the confusion. – Ð.. Jun 21 '18 at 15:10
  • Actually, it might just be easier to develop a custom macro for this... – Ð.. Jun 22 '18 at 16:37
  • To solve this, I ended up developing a custom macro. Boost Hana and other libraries may one day be able to support this - see [this GitHub issue](https://github.com/boostorg/hana/issues/409) on adding generalized annotations to Boost Hana - this would allow one to do Reflection on any sort of struct, whether they had default values, were arrays, or were bitfields, and so on... – Ð.. Jul 16 '18 at 19:19

0 Answers0