KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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.
Tags (comma-separated)
Save Edits
Cancel