Wrapper policy for doubles
Dan Bloomquist <[email protected]> Sun, 9 Sep 2018 11:50:09 -0700
| Newsgroups | gmane.comp.parsers.spirit.general |
|---|---|
| Message-ID | <[email protected]> |
Henri Menke wrote:
> You can have a look at Compound Attribute Rules [1] and find that in
>
> (a | b) a: A, b: Unused --> (a | b): optional<A>
>
> so you will always end up with an inferred attribute. Therefore I
> suggest that you alter the grammar slightly to
>
> *item_parser % x3::omit['{' >> *(x3::char_ - '}') >> '}']
Hi Henri,
A belated thanks. And I'm getting the hang of '%'. From there, I'm
trying to understand more about using parsers inside parsers. I had a
challenge to parse dollar amounts into doubles, so I came up with this.
I just don't know if there is a more elegant way to do it. I was able to
keep semantic action out of the bigger picture with this method. It did
give me a better understanding of attributes/values.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <iostream>
#include <boost/spirit/home/x3.hpp>
using namespace boost::spirit::x3;
auto sa = [](auto &ctx) {
_pass(ctx) = parse(begin(_attr(ctx)), end(_attr(ctx)), double_,
_val(ctx));
};
auto const mstr = rule<struct money_def, std::string>("mstr") =
-lit('$') >> *char_("0-9.") % ',';
auto const money = rule<struct money_def, double>("money") = mstr[sa];
int main()
{
std::vector<double> tv;
std::string ds("$1,234 $45,675 89.99");
parse(begin(ds), end(ds), money % ' ', tv);
for (auto& i : tv)
std::cout << i << std::endl;
return 0;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~