C++ macro/metaprogram to determine number of members at compile time

后端 未结 5 1550
鱼传尺愫
鱼传尺愫 2020-12-18 07:15

I am working on an application with a message based / asynchronous agent-like architecture. There will be a few dozen distinct message types, each represented by C++ types.<

5条回答
  •  抹茶落季
    2020-12-18 07:46

    There are several answers simply saying that it is not possible, and if you hadn't linked to magic_get I would've agreed with them. But magic_get shows, to my amazement, that it actually is possible in some cases. This goes to show that proving that something is not possible is harder than proving that something is possible!

    The short answer to your question would be to use the facilities in magic_get directly rather than reimplement them yourself. After all, even looking at the pre-Boost version of the code, it's not exactly clear how it works. At one point in the comments it mentions something about constructor arguments; I suspect this is the key, because it is possible to count the arguments to a regular function, so perhaps it is counting the number of arguments needed to brace-initialise the struct. This indicates that it may only be possible with plain old structs rather than objects with your own methods.

    Despite all this, I would suggest using a reflection library as others have suggested. A good one that I often recommend is Google's protobuf library, which has reflection and serialisation along with multi-language support. However, it is intended only for data-only objects (like plain old structs but with vectors and strings).

提交回复
热议问题