2016-11-29 15 views
2

我试过使用qi::uint_parser<int>()。但它与qi::uint_相同。它们全部匹配整数范围从0std::numeric_limits<unsigned int>::max()如何编写一个boost :: spirit :: qi解析器来解析从0到std :: numeric_limits的整数范围<int> :: max()?

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

+0

的可能的复制[约束existin g Boost.Spirit real \ _parser(with a policy)](http://stackoverflow.com/questions/30375750/constraining-the-existing-boost-spirit-real-parser-with-a-policy) – sehe

回答

4

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

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' 
+0

谢谢!我认为'_1> = 0'不需要语义动作,因为'uint_'已经完成了这项工作。我仍然好奇,qi :: uint_parser '和'qi :: uint_parser '之间是否有区别?看起来数字基类型“T”所需的'std :: numeric_limits :: max()'在这里没有使用。 – Han

相关问题