I have the following problem.
Given any type of T
:
template <typename T>
I need to be able to convert an object of type T
to a std::unordered_map<std::string, boost::any>
map containing an entry for each attribute. Initially I think of "flat" objects, with only primitive attributes and strings.
std::unordered_map<boost::any, boost::any>& asUnordered_map(const T& obj)
I also need to do the opposite, that is, given a std::map<std::string, boost::any>
and a T
object I want to update the attributes of the object:
T& asObject(const std::unordered_map<boost::any, boost::any>& map)
In Java a natural implementation would use Introspector
and techniques reflection .
It seems however that C ++ still does not support reflection by default (the committee and certain study groups are moving forward on that front for an upcoming release ) and emulating this functionality externally does a good job (see CPP-Reflection ). In this way I would like to know if there is a more idiomatic alternative to solve this type of problem.
How can I find out what the attributes of an object are and how can I retrieve / modify values of an unknown type in C ++?