【问题标题】:How to write a boost::spirit::qi parser to parse an integer range from 0 to std::numeric_limits<int>::max()?如何编写 boost::spirit::qi 解析器来解析从 0 到 std::numeric_limits<int>::max() 的整数范围?
【发布时间】:2016-11-29 12:58:25
【问题描述】:

我尝试使用qi::uint_parser&lt;int&gt;()。但它与qi::uint_ 相同。它们都匹配从0std::numeric_limits&lt;unsigned int&gt;::max() 的整数。

qi::uint_parser&lt;int&gt;() 是这样设计的吗?我应该使用什么解析器来匹配从0std::numeric_limits&lt;int&gt;::max() 的整数范围?谢谢。

【问题讨论】:

标签: c++ parsing numeric boost-spirit boost-spirit-qi


【解决方案1】:

最简单的演示,附加一个语义动作来做范围检查:

uint_ [ _pass = (_1>=0 && _1<=std::numeric_limits<int>::max()) ];

Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

template <typename It>
struct MyInt : boost::spirit::qi::grammar<It, int()> {
    MyInt() : MyInt::base_type(start) {
        using namespace boost::spirit::qi;
        start %= uint_ [ _pass = (_1>=0 && _1<=std::numeric_limits<int>::max()) ];
    }
  private:
    boost::spirit::qi::rule<It, int()> start;
};

template <typename Int>
void test(Int value, char const* logical) {
    MyInt<std::string::const_iterator> p;

    std::string const input = std::to_string(value);
    std::cout << " ---------------- Testing '" << input << "' (" << logical << ")\n";

    auto f = input.begin(), l = input.end();
    int parsed;
    if (parse(f, l, p, parsed)) {
        std::cout << "Parse success: " << parsed << "\n";
    } else {
        std::cout << "Parse failed\n";
    }

    if (f!=l) {
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
    }
}

int main() {
    unsigned maxint = std::numeric_limits<int>::max();

    MyInt<std::string::const_iterator> p;

    test(maxint  , "maxint");
    test(maxint-1, "maxint-1");
    test(maxint+1, "maxint+1");
    test(0       , "0");
    test(-1      , "-1");
}

打印

 ---------------- Testing '2147483647' (maxint)
Parse success: 2147483647
 ---------------- Testing '2147483646' (maxint-1)
Parse success: 2147483646
 ---------------- Testing '2147483648' (maxint+1)
Parse failed
Remaining unparsed: '2147483648'
 ---------------- Testing '0' (0)
Parse success: 0
 ---------------- Testing '-1' (-1)
Parse failed
Remaining unparsed: '-1'

【讨论】:

  • 谢谢!而且我认为不需要语义动作中的_1&gt;=0,因为uint_ 已经完成了这项工作。我仍然很好奇qi::uint_parser&lt;int&gt;qi::uint_parser&lt;unsigned int&gt; 之间有什么区别?似乎这里没有使用数字基类型T 所需的std::numeric_limits&lt;T&gt;::max()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2011-01-26
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多