2016-11-29 1 views
2

qi::uint_parser<int>()을 사용해 보았습니다. 그러나 qi::uint_과 같습니다. 모두 0에서 std::numeric_limits<unsigned int>::max()까지의 정수와 일치합니다.0에서 std :: numeric_limits <int> :: max() 정수 범위를 구문 분석하는 boost :: spirit :: qi 파서를 작성하는 방법?

qi::uint_parser<int>()은 이렇게 설계 되었습니까? 0에서 std::numeric_limits<int>::max()까지의 정수 범위와 일치 시키려면 어떤 파서를 사용해야합니까? 감사.

+0

가능한 중복을 [ g Boost.Spirit 실제 \ _parser (정책 포함)] (http://stackoverflow.com/questions/30375750/constraining-the-existing-boost-spirit-real-parser-with-a-policy) – sehe

답변

4

간단한 데모, 범위 체크 할 수있는 의미 작용 부착 다음 existin 구속

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

감사! 'uint_'는 이미 작업을했기 때문에 의미 론적 동작에서'_1> = 0'이 필요하지 않다고 생각합니다. 나는 아직도'qi :: uint_parser '와'qi :: uint_parser '사이에 어떤 차이점이 있는지 궁금하다. 숫자 형 타입'T'에 대해'std :: numeric_limits :: max()'가 필요하지 않은 것 같습니다. – Han

관련 문제