如何编写boost :: spirit :: qi解析器以解析从0到std :: numeric_limits< int> :: max()的整数范围? [英] How to write a boost::spirit::qi parser to parse an integer range from 0 to std::numeric_limits<int>::max()?

查看:137
本文介绍了如何编写boost :: spirit :: qi解析器以解析从0到std :: numeric_limits< int> :: max()的整数范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用qi::uint_parser<int>().但这和qi::uint_一样.它们都匹配从0std::numeric_limits<unsigned int>::max()的整数.

I tried to use qi::uint_parser<int>(). But it is the same like qi::uint_. They all match integers range from 0 to std::numeric_limits<unsigned int>::max().

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

Is qi::uint_parser<int>() designed to be like this? What parser shall I use to match an integer range from 0 to std::numeric_limits<int>::max()? Thanks.

推荐答案

最简单的演示,附加语义动作以进行范围检查:

Simplest demo, attaching a semantic action to do the range check:

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

在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'

这篇关于如何编写boost :: spirit :: qi解析器以解析从0到std :: numeric_limits&lt; int&gt; :: max()的整数范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆