问题描述
是否可以在 C++ 中遍历 Struct 或 Class 以找到其所有成员?例如,如果我有 struct a 和 class b:
Is it possible in C++ to iterate through a Struct or Class to find all of its members? For example, if I have struct a, and class b:
是否可以循环它们说得到一个打印语句,说结构 a 具有名为 a、b、c 的 int"或b 类具有名为 a、b、c 的 int"
Would it be possible to loop them to say get a print statement saying "Struct a has int named a, b, c" or "Class b has int named a, b, c"
推荐答案
有几种方法可以做到这一点,但您需要使用一些宏来定义或调整结构.
There are a couple of ways to do this, but you need to use some macros to either define or adapt the struct.
您可以使用 this answer 中给出的 REFLECTABLE
宏来定义这样的结构:
You can use the REFLECTABLE
macro given in this answer to define the struct like this:
然后你可以遍历字段并像这样打印每个值:
And then you can iterate over the fields and print each value like this:
另一种方法是将结构调整为融合序列(参见 文档).举个例子:
Another way is to adapt the struct as a fusion sequence (see the documentation). Here's an example:
然后您也可以使用此打印字段:
Then you can print the fields as well using this:
这篇关于遍历结构和类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!