我正在学习boost::spirit
,我正在尝试阅读一些文本并将其解析为结构。
例如,在我的下面"2: 4.6"
被解析为 int2
和 double :4.6
TestStruct
#include <iostream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/fusion/include/std_pair.hpp>
namespace qi = boost::spirit::qi;
struct TestStruct {
int myint;
double mydouble;
TestStruct() {}
TestStruct(std::pair<int,double> p) : myint(p.first), mydouble(p.second) {}
};
template <typename Iterator, typename Skipper>
struct MyGrammar : qi::grammar<Iterator, TestStruct(), Skipper> {
MyGrammar() : MyGrammar::base_type(mystruct) {
mystruct0 = qi::int_ >> ":" >> qi::double_;
mystruct = mystruct0;
}
qi::rule<Iterator, std::pair<int,double>(), Skipper> mystruct0;
qi::rule<Iterator, TestStruct(), Skipper> mystruct;
};
int main() {
typedef boost::spirit::istream_iterator It;
std::cin.unsetf(std::ios::skipws);
It it(std::cin), end; // input example: "2: 3.4"
MyGrammar<It, qi::space_type> gr;
TestStruct ts;
if (qi::phrase_parse(it, end, gr, qi::space, ts) && it == end)
std::cout << ts.myint << ", " << ts.mydouble << std::endl;
return 0;
}
它工作得很好,但我想知道如何简化这段代码?
例如,我想摆脱mystruct0
语法规则,该规则仅用于标记类型std::pair<int,double>
,然后用于从规则中自动构造TestStruct
对象。mystruct
如果可能的话,我还希望能够摆脱TestStruct
构造函数std::pair
。
那么,下面的代码可以以某种方式进行编译吗?那将是一个更好的解决方案:
struct TestStruct {
int myint;
double mydouble;
TestStruct() {}
TestStruct(int i, double d) : myint(i), mydouble(d) {}
};
template <typename Iterator, typename Skipper>
struct MyGrammar : qi::grammar<Iterator, TestStruct(), Skipper> {
MyGrammar() : MyGrammar::base_type(mystruct) {
mystruct = qi::int_ >> ":" >> qi::double_;
}
qi::rule<Iterator, TestStruct(), Skipper> mystruct;
};
int main() {
typedef boost::spirit::istream_iterator It;
std::cin.unsetf(std::ios::skipws);
It it(std::cin), end; // input example: "2: 3.4"
MyGrammar<It, qi::space_type> gr;
TestStruct ts;
if (qi::phrase_parse(it, end, gr, qi::space, ts) && it == end)
std::cout << ts.myint << ", " << ts.mydouble << std::endl;
return 0;
}
不幸的是,编译器说:
boost_1_49_0/include/boost/spirit/home/qi/detail/assign_to.hpp:123:
error: no matching function for call to ‘TestStruct::TestStruct(const int&)’