0

I'm trying to do yet another reflection library for C++, one feature that I want is to check at compile time that user enumerate all struct fields and all of them in right order(this part was easy). I tried to just sum member sizes and compare to size of whole struct, but this doesn't work cause padding. Any way to do this? Like get sizeof member + padding in struct.

struct Test {
  bool a;
  float b;
};
static_assert(sizeof(Test) == sizeof(Test::a) + sizeof(Test::b));
Vladyslav Mozhvylo
  • 331
  • 1
  • 2
  • 11
  • What do you mean by "enumerate all struct fields", exactly? – Dai Jul 21 '20 at 10:57
  • Your whole idea will fail if the code packs the struct explicitly using `attribute` or a `#pragma`. – PaulMcKenzie Jul 21 '20 at 10:57
  • I mean that if we have struct with two fields but we enumerate only one in macro - we got compilation error. – Vladyslav Mozhvylo Jul 21 '20 at 10:58
  • Right now I have something like this `REFLECTION_ADAPT_STRUCT(Test, a, b)`, it should not compile if I write just `REFLECTION_ADAPT_STRUCT(Test, b)` or `REFLECTION_ADAPT_STRUCT(Test, b, a)`(this is already done) – Vladyslav Mozhvylo Jul 21 '20 at 10:59
  • 1
    You can probably peek at [magic get](https://github.com/apolukhin/magic_get#motivating-example-0) implementation – dewaffled Jul 21 '20 at 10:59
  • `magic_get` don't work with inheritance and type should be aggregated – Vladyslav Mozhvylo Jul 21 '20 at 11:00
  • Maybe you could leverage the fact that structured bindings must exactly match the number of public non-static data members? – dfrib Jul 21 '20 at 11:13
  • Testing presence of data members and/or base classes of non-aggregate is anyway impossible on general case as your "reflector code" may lack access to (or even visibility of) those in common C++ code bases. Such level of analysis tools need to parse source code. Perhaps use clangs frontend, it is open source with liberal license. – Öö Tiib Jul 21 '20 at 11:13
  • I tried clang to parse source code, but this will be +1 compilation step for all project – Vladyslav Mozhvylo Jul 21 '20 at 11:16
  • This seems related https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member – Yunnosch Jul 21 '20 at 11:18
  • Performance requirements of viable solutions weren't even part of your question. :D Most deep analysis steps can be made optional and unneeded in development ... for example as an automatic check of pull request ... by continuous integration. – Öö Tiib Jul 21 '20 at 11:36

0 Answers0