Two stackoverflow answers suggest the approach using fusion adapt_struct to iterate over struct fields. The approach looks nice. However, how do you iterate into a field which itself is a struct?
Following the previous answers, I come up with the code below. The problem is at the “#if 0” clause the code does not compile. As an alternative solution I created “decode()” function to take a void pointer to the target argument. That works, but loses the type information at compile time. Is there a better solution?
struct Foo_s { int i; };
BOOST_FUSION_ADAPT_STRUCT( Foo_s, (int, i) )
struct Bar_s { int v; Foo_s w; };
BOOST_FUSION_ADAPT_STRUCT( Bar_s, (int, v) (Foo_s, w) )
struct AppendToTextBox {
template <typename T> void operator()(T& t) const {
int status = 0;
const char *realname = abi::__cxa_demangle(typeid(t).name(), 0, 0, &status);
printf(" typename: %s value: %s realname: %s\n", typeid(t).name(),
boost::lexical_cast<std::string>(t).c_str(), realname);
std::string rn(realname);
if ( rn.rfind("_s") == rn.size()-2 ) {
#if 0 /* this can not compile */
for_each(t, AppendToTextBox());
#else
decode(&t, rn);
#endif
}
}
};
void decode(void *f, std::string & intype ) {
if ( intype.find("Foo_s") == 0 )
for_each( *(Foo_s *)f, AppendToTextBox());
};
int main(int argc, char *argv[]) {
Bar_s f = { 2, { 3 } };
for_each(f, AppendToTextBox());
return 0;
}
I have seen on wikipedia instead of passing a type string “intype” you can use typeid and dynamic_cast. But that will only be a minor improvement. I’m looking for a solution that is more intrinsic to C++ or boost language design.
I made an example of what you want that you can see at my blog site. In this is case it’s a JSON serializer that works with nested structs. It uses a ‘more Boost’ solution since I saw it in the Boost.Serialization library. (See also below and live on Coliru.)
The solution uses Fusion Sequence adaptation of structs and a metafunction that walks object members (recursively) – using Boost.TypeTraits and different traits for specific types.
You can see a more complex example of the same solution at the site for googlecode corbasim project for creating an run-time reflexive API.
Code listing for the generic JSON serializer:
See it Live on Coliru