我需要跟踪我正在使用Boost Spirit Qi解析的文本中某些项目的位置。我找到了this example,并适应了:
#include <iostream>
#include <string>
#include <boost/spirit/home/qi.hpp>
#include <boost/spirit/repository/include/qi_iter_pos.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace phx = boost::phoenix;
namespace qi = boost::spirit::qi;
template<typename Iterator>
struct CurrentPos
{
CurrentPos()
{
save_start_pos = qi::omit[boost::spirit::repository::qi::iter_pos[
phx::bind(&CurrentPos::setStartPos, this, qi::_1)]];
current_pos = boost::spirit::repository::qi::iter_pos[
qi::_val = phx::bind(&CurrentPos::getCurrentPos, this, qi::_1)];
}
qi::rule<Iterator> save_start_pos;
qi::rule<Iterator, std::size_t()> current_pos;
private:
void setStartPos(const Iterator &iterator)
{
start_pos_ = iterator;
}
std::size_t getCurrentPos(const Iterator &iterator)
{
return std::distance(start_pos_, iterator);
}
Iterator start_pos_;
};
using InfoTuple = std::tuple<std::size_t, std::uint32_t>;
struct Header
{
std::uint32_t x;
InfoTuple y;
};
BOOST_FUSION_ADAPT_STRUCT(
Header,
(std::uint32_t, x)
(InfoTuple, y)
)
template<typename Iterator>
struct HeaderParse
: boost::spirit::qi::grammar<Iterator, Header()>
{
HeaderParse()
: HeaderParse::base_type(_start)
{
using boost::spirit::qi::uint_parser;
_thing = (current_pos.current_pos >> uint_parser<std::uint32_t, 10, 1, 3>());
_start = current_pos.save_start_pos
>> '<'
>> uint_parser<std::uint32_t, 10, 1, 3>()
>> '>'
>> _thing;
}
qi::rule<Iterator, InfoTuple()> _thing;
qi::rule<Iterator, Header()> _start;
CurrentPos<Iterator> current_pos;
};
int main()
{
const std::string d1 = "<13>937";
const HeaderParse<std::string::const_iterator> parser;
Header header;
std::string::const_iterator begin = d1.begin();
std::string::const_iterator end = d1.end();
assert(boost::spirit::qi::parse(begin, end, parser, header));
assert(begin == end);
std::cout << "x : " << header.x << std::endl;
std::cout << "y : " << std::get<1>(header.y) << std::endl;
std::cout << "y pos: " << std::get<0>(header.y) << std::endl;
}
运行它时,我看到以下输出:
$> ./testme
x : 13
y : 0
y pos: 4
由于某种原因,它将无法捕获值937
。
我在Coliru上尝试了此操作,起初它没有编译,现在我不断“执行过期”。参见此处:https://coliru.stacked-crooked.com/a/724c7fcd296c8803但这使我想知道它是否有效。我正在使用clang,而Coliru正在使用gcc。
有人可以提供任何有关为什么这种方法行不通的见解吗?
答案 0 :(得分:1)
由于缺少Fusion std::tuple
集成头(boost/fusion/include/std_tuple.hpp
),您的示例无法为我编译。添加示例后,该示例将编译并输出预期结果。 https://wandbox.org/permlink/wOf8JxnKKeBGCihk
P.S:我建议不要为解析器中的偏移量计算而烦恼,它不会为您节省任何费用,因为存储迭代器本身具有相同的内存占用空间,但复杂度和痛苦程度较小。