Enumerate members of a structure?

前端 未结 6 940
渐次进展
渐次进展 2021-01-13 10:02

Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I\'ve used the following sample code b

6条回答
  •  失恋的感觉
    2021-01-13 10:10

    To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).

    If you have control over your data structure, you could try a std::vector or a std::map then add all your member variables to the vector/map.

    Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.

提交回复
热议问题