当我将输入解析为std :: string时,我得到了字符串,但是当我将其解析为double_时,fusion struct包含一些非常小的数字而不是预期的数字。
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <string>
// http://www.boost.org/doc/libs/1_57_0/libs/spirit/example/qi/employee.cpp
namespace FormatConverter {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
// TODO: should this have an initializer?
struct asc {
double timestamp;
};
}
BOOST_FUSION_ADAPT_STRUCT(
FormatConverter::asc,
(double, timestamp)
)
namespace FormatConverter {
template <typename Iterator>
struct asc_parser : qi::grammar< Iterator, asc(), ascii::space_type >
{
asc_parser()
: asc_parser::base_type(start) {
timestamp %= qi::double_ ;
start %= timestamp ;
;
}
qi::rule< Iterator, double, ascii::space_type > timestamp;
qi::rule< Iterator, asc(), ascii::space_type > start;
};
}
我正在测试这个:
#define BOOST_TEST_MODULE parser
#include <boost/test/included/unit_test.hpp>
#include "../FormatConverter/FormatConverter.h"
#include <string>
BOOST_AUTO_TEST_SUITE( TestSuite1 )
BOOST_AUTO_TEST_CASE( timestamp ) {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
using iterator_type = std::string::iterator;
using parser_type = FormatConverter::asc_parser<iterator_type>;
parser_type grammar;
FormatConverter::asc record;
std::string str("161.096841 ");
auto beg = str.begin();
auto end = str.end();
auto success = qi::phrase_parse(beg, end, grammar, ascii::space, record);
BOOST_REQUIRE(success);
BOOST_REQUIRE(beg==end);
std::cout << "timestamp: " << boost::fusion::as_vector(record) << std::endl;
}
BOOST_AUTO_TEST_SUITE_END()
答案 0 :(得分:6)
您错过了属性中的()
:
qi::rule< Iterator, double, ascii::space_type > timestamp;
应该是
qi::rule< Iterator, double(), ascii::space_type > timestamp;
因为qi::rule
中的params顺序可以是任意的(Iterator除外),所以lib内部使用一些特征来识别哪个是attr,哪个是headper,等等。 attr字段必须采用function-sig的形式,即synthesized(inherited)
,如果你写double
,它将不被识别为attr,所以你的timestamp
规则实际上是有unused_type
而不是double
作为其attr,这意味着,record.timestamp
将不会被解析器填充,它是未初始化的。