[xsd-users] xs:choice representation in C++

Gershanovich, Leonid leonid.gershanovich at 247realmedia.com
Mon Sep 28 00:56:45 EDT 2009


Boris,

I was wondering if you considered to use something like boost::variant (http://www.boost.org/doc/libs/1_40_0/doc/html/variant.html) for mapping xs:choice to c++.
It seems that representing following xsd construct:
<xs:choice>
  <xs:element name="stringEl" type="xs:string"/>
  <xs:element name="intEl" type="xs:int"/>
</xs:choice>

As
typedef string stringEl_type;
typedef int     intEl_type;

boost::variant < stringEl_type , intEl_type  > m_choicer;

Is little cleaner in terms of expressing intended object model than

optional < string > stringEl;
optional < int > intEl;

Besides this way it will be harder to forget handling a specific choice, as instead of series of statements like:

If (stringEl.present())
{
...
}

If (intEl.present())
{
...
}

boost:variant will let compiler check if overloads for every type in the choice have been defined, thus developer is less likely to forget to handle a particular "choice". This is especially true for schemas that are under active development.

class my_visitor : public boost::static_visitor<int>
{
public:
    int operator()(intEl_type i) const
    {
        return i;
    }

    int operator()(const stringEl_type & str) const
    {
        return str.length();
    }
};


What do you think?

Leonid



More information about the xsd-users mailing list