1

I am writing some C++ that reads an XML string and populates some struct members with values matching attribute keys in the XML file. At the moment, the first pass at this makes a stl::unordered_map of key - value pairs. The next step is to interpret the value strings and return them as their destination types to be stored in the structs. Some of the types are a bit complicated but I have methods that can convert them.

What I want to do is use an mpl::vector to map the keys to the struct members using the get_value_* methods to convert the values. I think it will look a bit like:

typedef boost::mpl mpl;
using namespace std;

template<string K, typename T, T& dest, boost::function<void(MapTypePtr, string, T& dest)> >
struct MapperRow {};

struct Mapper : mpl::vector<
    MapperRow < "death_star_radius", Length, death_star.radius, get_value_units >,
    MapperRow < "death_star_energy", Energy, death_star.energy, get_value_units >,
    MapperRow < "operational",       bool,   death_star.operational, get_value_simple >,
    MapperRow < "num_tie_fighters",  int,    death_star.tie_fighers, get_value_simple >
> {};

The Length and Energy types are typedefs of boost::units::quantities.

Is this doable with boost metaprogramming? If I'm on the right track, how do I make it run? Do I need to iterate mpl::vector?

Matthew Smith
  • 6,165
  • 6
  • 34
  • 35
  • I don't understand the question yet, but you can't use classes like strings in the template declaration the way you do. That only works with basic types like 'bool' or 'unsigned'. – Peter Dec 13 '12 at 01:52
  • There might be an mpl wrapper type that does it somehow? I might be asking the impossible but I've seen something similar with boost state machines so I'm hoping I can get close. – Matthew Smith Dec 13 '12 at 01:56
  • Yes, there are ways. Not pretty tough (use a template that has many characters as arguments). For this I found it's often easier to use a code generator which might be simple in your case because you already have the XML and only need an xsl or some other kind of translator to generate the code. – Peter Dec 13 '12 at 02:06
  • `struct death_star_radius { const char* value() { return "death_star_radius"; } };` type stuff can be used to represent a string as a type. In C++11, `struct { const char* value() { return "death_star_radius"; } }` as an anonymous type also works. Sadly, string literals cannot be used as direct template arguments as far as I know. – Yakk - Adam Nevraumont Dec 13 '12 at 03:23
  • This article http://cpp-next.com/archive/2012/10/using-strings-in-c-template-metaprograms/ provides some insight into using strings within template metaprograms. – mark Dec 13 '12 at 08:15
  • Since you read the keys from a file, how do you expect to use them as template arguments? You would need some sort of switch for "converting" the runtime value to a compile-time value, which would defeat the purpose of having a map in the first place. Well, you could also achieve your goal by iterating at compile-time over the map to find the key corresponding to the runtime value, but is it really worth the trouble? – Luc Touraille Feb 20 '13 at 11:58

1 Answers1

1

This is definitively possible (see below), but I'm not sure it's worth the trouble... Couldn't you use a simpler approach, perhaps with inheritance and polymorphism?

Nevertheless, here is a working solution using Boost.MPL:

// MapperRow holds the necessary parsing informations: type of the member,
// type of the object, pointer to the appropriate member, parsing function
template<typename Type, typename Clazz, Type Clazz::*Member, 
         void (*Parser)(const std::string &, Type &)>
struct MapperRow
{
    typedef Type type;
    typedef Clazz clazz;
    typedef Type Clazz::*memberType;
    static const memberType member;
    typedef void (*parserType)(const std::string &, Type &);
    static const parserType parser;
};

template <typename Type, typename Clazz, Type Clazz::*Member,
          void (*Parser)(const std::string &, Type &)>
const typename MapperRow<Type, Clazz, Member, Parser>::memberType
    MapperRow<Type, Clazz, Member, Parser>::member = Member;

template <typename Type, typename Clazz, Type Clazz::*Member,
          void (*Parser)(const std::string &, Type &)>
const typename MapperRow<Type, Clazz, Member, Parser>::parserType
    MapperRow<Type, Clazz, Member, Parser>::parser = Parser;


// fill iterates over a map key->MapperRow, trying to find the given key.
// if found, it calls the parsing function, otherwise it asserts false (should
// probably throw an exception instead)
template <typename Clazz, typename First, typename Last>
struct fill_impl
{
    static void apply(Clazz &obj, const std::string &key,
                      const std::string &value)
    {
        typedef typename mpl::deref<First>::type entry;
        static const char *curKey = 
            mpl::c_str< typename 
                mpl::first<entry>::type
            >::value;

        if (key == curKey)
        {
            typedef typename mpl::second<entry>::type Row;

            Row::parser(value, obj.*Row::member);
        }
        else
        {
            fill_impl<
                Clazz, typename
                mpl::next<First>::type,
                Last
            >::apply(obj, key, value);
        }
    }
};

template <typename Clazz, typename Last>
struct fill_impl<Clazz, Last, Last>
{
    static void apply(Clazz &obj, const std::string &key,
                      const std::string &value)
    {
        assert(false && "key not found");
    }
};

template <typename Map, typename Clazz>
void fill(Clazz &obj, const std::string &key, const std::string &value)
{
    fill_impl< 
        Clazz, typename 
        mpl::begin<Map>::type, typename 
        mpl::end<Map>::type
    >::apply(obj, key, value);
}

Sample use:

template <typename T>
void get_value_units(const std::string &str, T &value)
{
    value = T::from_value(boost::lexical_cast<typename T::value_type>(str));
}

template <typename T>
void get_value_simple(const std::string &str, T &value)
{
    value = boost::lexical_cast<T>(str);
}

typedef boost::units::quantity<boost::units::si::energy> Energy;
typedef boost::units::quantity<boost::units::si::length> Length;

struct DeathStar
{
    Length radius;
    Energy energy;
    bool operational;
    int tie_fighters;
};

// Could be clearer with MPLLIBS_STRING*
typedef mpl::map<
    mpl::pair<
        mpl::string<'deat','h_st','ar_r','adiu','s'>, 
        MapperRow< Length , DeathStar, &DeathStar::radius, 
                   &get_value_units<Length> > >,
    mpl::pair<
        mpl::string<'deat','h_st','ar_e','nerg','y'>,
        MapperRow< Energy, DeathStar, &DeathStar::energy, 
                   &get_value_units<Energy> > >,
    mpl::pair< 
        mpl::string<'oper','atio','nal'>, 
        MapperRow< bool, DeathStar, &DeathStar::operational, 
                   &get_value_simple<bool> > >,
    mpl::pair< 
        mpl::string<'num_','tie_','figh','ters'>, 
        MapperRow< int, DeathStar, &DeathStar::tie_fighters, 
                   &get_value_simple<int> > >
> death_star_map;

int main()
{
    DeathStar ds;
    fill<death_star_map>(ds, "death_star_radius", "12");
    fill<death_star_map>(ds, "death_star_energy", "34");
    fill<death_star_map>(ds, "operational", "1");
    fill<death_star_map>(ds, "num_tie_fighters", "56");

    std::cout << "Radius: " << ds.radius << '\n';
    std::cout << "Energy: " << ds.energy << '\n';
    std::cout << "Operational: " << std::boolalpha << ds.operational << '\n';
    std::cout << "Tie fighters: " << ds.tie_fighters << '\n';
}

* MPLLIBS_STRING

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
  • Thanks for your answer. No it's not worth the trouble but for me it seemed like something that should be possible and would help me understand mpl. I will mediate on your answer and see if I achieve enlightenment! – Matthew Smith Mar 11 '13 at 03:24