Is there a way to statically iterate over all members of a C++ struct?
Say if we have many predefined structs which look like:
struct Foo {
int field1;
double field2;
char field3;
...
int field9;
};
struct Bar {
double field14;
char field15;
int field16;
bool field17;
...
double field23;
};
And we want to have a template function
template<typename T>
void Iterate(T object);
so that Iterate
can run a template function Add
over all the members of type T
. For example, Iterate<Foo>
and Iterate<Bar>
would become
void Iterate<Foo>(Foo object) {
Add<int>(object.field1);
Add<double>(object.field2);
Add<char>(object.field3);
...
Add<int>(object.field9);
}
void Iterate<Bar>(Bar object) {
Add<double>(object.field14);
Add<char>(object.field15);
Add<int>(object.field16);
Add<bool>(object.field17);
...
Add<double>(object.field23);
}
This can be done by writing another program that parses the struct
definition and generate a cpp
file, but that would be too cumbersome and requires additional compiling and execution.
Edit: The struct may have many fields, and they are predefined, so it can't be changed into other types. Also this is at compile-time, so it has less to do with "reflection", which is performed at run-time, and more to do with "template programming" or "metaprogramming". We have <type_traits>
for type inspection at compile-time, but that does not seem to be enough.