I played around with boost::spirit recently and wanted to use it to parse file input. What i got is this: defining some semantic actions:
data = ifstream("herpderp", ios::in);
std::string line;
auto pri = [&](auto &ctx){cout << "got this" << endl;};
auto bri = [&](auto &ctx){cout << "got that" << endl;};
and the actual reading happens like this:
while(getline(data, line, '\n'))
{
bool r = phrase_parse(line.begin(), line.end(), (int_ >> char_ >> int_ >> double_)[pri] | (int_ >> char_ >> int_)[bri], space);
}
However the problem is - I have no idea how to access the contents of _attr(ctx)
inside the lambdas pri
and bri
. I know they work as intended, depending on the contents of the file because of the cout
prints (they alternate) - they are however compound type as one can tell from the parsing rules. If anyone can shed some light on this, I'd be grateful.
Edit: Got this to work the way I wanted it to. It required another import
#include <boost/mpl/int.hpp>
And each of the lambdas looks like this:
auto bri = [&](auto &ctx)
{
int firstIntFromMatch = at<boost::mpl::int_<0>>(_attr(ctx));
char charFromMatch = at<boost::mpl::int_<1>>(_attr(ctx));
int secondIntFromMatch = at<boost::mpl::int_<2>>(_attr(ctx));
doSomething(firstIntFromMatch, charFromMatch, secondIntFromMatch);
};
auto pri = [&](auto &ctx)
{
int firstIntFromMatch = at<boost::mpl::int_<0>>(_attr(ctx));
char charFromMatch = at<boost::mpl::int_<1>>(_attr(ctx));
int secondIntFromMatch = at<boost::mpl::int_<2>>(_attr(ctx));
double doubleFromMatch = at<boost::mpl::int_<3>>(_attr(ctx));
doSomething(firstIntFromMatch, charFromMatch, secondIntFromMatch);
doSomethingElse(doubleFromMatch);
};