1

I would like to know how to write a C++ function to print the attributes of a generic struct. For example,

struct a {
std::string field_1;
std::string field_2;
std::string field_3;
};


struct b {
int a;
int b;
int c;
};

The function would take struct of form 'a' or 'b'as inputs and generate outputs. Perhaps a template could be used -- if so how would one build it?

K Alistair
  • 15
  • 4

3 Answers3

2

This is not possible in standard C++, it does not work this way. C++ does not have reflection.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
1

This is currently not possible but might be available in C++17 with static reflection.

See also Compile-time reflection in C++1z?

Community
  • 1
  • 1
Henricus V.
  • 898
  • 1
  • 8
  • 29
0

There are two possibilities to work around the missing support for reflections in c++.

The first one is to use std::tuple instead and iterate over it. This can be done explicitly by reflection or nicely wrapped in boost::fusion.

The second posibillity with c++14 is boost::hana. In boost::hana there are structs, that can be iterated over. This is done with the help of preprocessor macros.

If you are still interested, i can post a minimal example here.

OutOfBound
  • 1,914
  • 14
  • 31