Search code examples
c++parsingboost-spiritboost-spirit-qiboost-fusion

How can I parse different structures with Boost.Spirit.Qi?


In this example, employee structs are parsed in the form "employee{int, string, string, double}".

I would like to know whether it is possible to modify this example to also parse different types of structs, like "intern{int, string, string}".

Specifically, I would like to then pass the structure to a function overloaded on the structure type. It would be great if I can avoid using polymorphic double dispatch for this, and instead preserve the concrete type that gets parsed to statically match the correct overloaded function.


Solution

  • Sure, that's possible. Create a rule for each of the types you want to parse:

    rule<Iterator, std::string()> s = ...;
    rule<Iterator, intern()> intern_r = int_ >> s >> s;
    rule<Iterator, employee()> employee_r = int_ >> s >> s >> double_;
    

    and combine those into an alternative:

    rule<Iterator> r = 
            intern_r   [phoenix::bind(receive_intern, _1)]
        |   employee_r [phoenix::bind(receive_employee, _1)]
        ;
    

    This assumes you have 2 functions handling the parsed data:

    void receive_intern(intern const&);
    void receive_employee(employee const&);
    

    Is that what you want?