[xsd-users] comparison question
Boris Kolpackov
boris at codesynthesis.com
Mon Jun 30 16:35:01 EDT 2008
Hi Ray,
Rizzuto, Raymond <Raymond.Rizzuto at sig.com> writes:
> 1) make the compiler generate MessageType_base
> 2) derive my MessageType from MessageType_base
Correct.
> 3) repeat #1 and #2 for the 36 types derived from MessageType
Ok, the fact that you have 36 types makes this solution a lot less
attractive than if you had, say, 3 derived types.
One alternative (which we will most likely use in the generated code)
would be to have a map of type_info to pointer to operator== (actually,
it will have to be a pointer to a "thunk" function which calls operator==).
Then operator== for MessageType would lookup the proper operator== and
call it.
This way instead of customizing 36 derived types you will just need
to add 36 entries to the map. Here is how this may look:
typedef bool (*compare) (const MessageType&, const MessageType&);
typedef std::map<const std::type_info*, compare, type_info_comparator> map;
template <typename X>
bool compare_thunk (const MessageType& a, const MessageType& b)
{
const X& ax = static_cast<X> (a);
const X& bx = static_cast<X> (b);
return ax == bx;
}
map cmp_map; // global map
bool operator== (const MessageType& a, const MessageType& b)
{
if (typeid (a) != typeid (b))
return false;
map::const_iterator i = cmp_map.find (&typeid (a));
if (i != cmp_map.end ())
{
compare c = i->second;
return c (a, b);
}
else
return false; // Missing map entry?
}
int
main ()
{
cmp_map[&typeid (MessageType1)] = &compare_thunk<MessageType1>;
cmp_map[&typeid (MessageType2)] = &compare_thunk<MessageType2>;
...
}
We use this approach to do polymorphism-aware serialization. If you
would like to take a look at the actual implementation, see the
type-serializer-map.* files in libxsd/xsd/cxx/tree/.
> 4) implement operator== for MessageType and have it call a virtual
> compare function
> 5) implement virtual compare function in the derived classes of
> MessageType
Correct again.
Boris
More information about the xsd-users
mailing list