我正在使用 boost::spirit 将文本解析为包含固定大小数组的结构。在遵循示例时
并尝试使用它来解析包含 std::array (或 boost::array)的结构,我认识到由于BOOST_FUSION_ADAPT_STRUCT的工作原理,我必须将助手result_of::adapt_array< some_array_type >::type放在结构也是如此。
我认为应该可以使用BOOST_FUSION_ADAPT_ADT创建一个包装器,但只是为了摆脱结构中的小适配器开销似乎有点过头了。由于我没有很多实例,从记忆的角度来看,我可以忍受它,但它也会引入一些噪音。
我还认为可以创建一个从数组类型派生的适配器,而不是封装它以隐藏一些噪音,但它会迫使我改变所有现有的结构,并且它会将解析器开销泄漏到外部,这不是很好的解决方案。
是否有一些明显的问题我正在接近错误,或者确实存在新的助手,它们在后台路由开销以便可以将它们封装在解析器中?
我知道 使用 std::array 作为 boost::spirit::x3 的属性。
这是我当前的代码:
#include <string>
#include <array>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
// ...code from http://www.boost.org/doc/libs/1_60_0/libs/spirit/example/qi/boost_array.cpp here
typedef result_of::adapt_array<std::array<double, 6> >::type AdaptedArrayType;
struct StructWithArray
{
StructWithArray()
: adaptedAry_(ary_)
{}
double dummy_; // see https://stackoverflow.com/questions/19823413/spirit-qi-attribute-propagation-issue-with-single-member-struct
std::array<double, 6> ary_;
AdaptedArrayType adaptedAry_;
};
BOOST_FUSION_ADAPT_STRUCT(
StructWithArray
,
(double, dummy_)
(AdaptedArrayType, adaptedAry_)
)
template <typename Iterator, typename Skipper>
struct StructWithArrayParser
: qi::grammar<Iterator, StructWithArray(), Skipper>
{
StructWithArrayParser() : StructWithArrayParser::base_type(start)
{
using qi::double_;
arrayLine %= double_ > double_ > double_ > double_ > double_ > double_;
start %= double_ > arrayLine;
}
qi::rule<Iterator, AdaptedArrayType(), Skipper> arrayLine;
qi::rule<Iterator, StructWithArray(), Skipper> start;
};
int main() {
std::string arrayStr = "0 1 2 3 4 5 6";
std::string::const_iterator it = arrayStr.begin();
std::string::const_iterator endIt = arrayStr.end();
StructWithArrayParser<std::string::const_iterator, ascii::space_type> grammar;
StructWithArray structWithArray;
bool ret = phrase_parse(it, endIt, grammar, ascii::space, structWithArray);
return 0;
}