I have a grammar similar to the following:
ruleFormat %= ruleComment | ruleSpec;
ruleFile %= ruleFormat % ruleNewline;
And the rules are declared like this:
rule<Iterator, void()> ruleComment;
rule<Iterator, int()> ruleSpec, ruleFormat;
rule<Iterator, std::vector<int>()> ruleFile;
(I actually do not use int, but a structure with some intin it).
Well, the grammar seems to work fine: when it ruleSpecmatches an integer, the rule has this attribute, which in turn is passed to the vector.
The problem is what ruleCommentmatches in ruleFormat, because the data is set to zero, and the zero value is placed inside the vector. As a result, the vector is filled with a combination of “correct” values and “wrong” zeros.
How can I prevent this?
EDIT: as requested, here is a sample code:
template <typename Iterator>
struct MyGrammar: public qi::grammar<Iterator, std::vector<int>()> {
MyGrammar(): MyGrammar::base_type(ruleFile) {
ruleComment = qi::lit('@');
ruleSpec %= qi::int_;
ruleFormat %= ruleComment | ruleSpec;
ruleFile %= ruleFormat % ' ';
ruleComment.name("COMMENT");
ruleSpec.name("SPEC");
ruleFormat.name("FORMAT");
ruleFile.name("FILE");
qi::debug(ruleComment);
qi::debug(ruleSpec);
qi::debug(ruleFormat);
qi::debug(ruleFile);
}
qi::rule<Iterator, void()> ruleComment;
qi::rule<Iterator, int()> ruleSpec, ruleFormat;
qi::rule<Iterator, std::vector<int>()> ruleFile;
};
int main() {
typedef std::string::const_iterator Iter;
std::string subj = "0 @ @ 12 3 @ 4 @ 56 @ ";
MyGrammar<Iter> gram;
qi::parse(subj.cbegin(), subj.cend(), gram);
return 0;
}
From the debug information, I get:
<attributes>[[0, 0, 0, 12, 3, 0, 4, 0, 56, 0]]</attributes>
, 0 , @
<attributes>[[0, 12, 3, 4, 56]]</attributes>