2012-11-07 45 views
8

我正在尋找一種方法來解析一個字符串爲int或double,解析器應該嘗試兩種選擇並選擇匹配輸入流的最長部分。使用boost精神解析int或double(longest_d)

有一個過時的指令(longest_d),它正是我在尋找:

number = longest_d[ integer | real ]; 

...因爲它過時了,還有其他的選擇嗎?如果需要實現語義行爲以實現所需的行爲,是否有人有建議?

回答

13

首先,請切換到Spirit V2 - 這已經取代傳統精神多年。

其次,你需要確定一個int是首選。默認情況下,雙可以解析任意整數同樣出色,所以你需要使用strict_real_policies代替:

real_parser<double, strict_real_policies<double>> strict_double; 

現在,你可以簡單地陳述

number = strict_double | int_; 

查看測試程序Live on Coliru

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

using namespace boost::spirit::qi; 

using A = boost::variant<int, double>; 
static real_parser<double, strict_real_policies<double>> const strict_double; 

A parse(std::string const& s) 
{ 
    typedef std::string::const_iterator It; 
    It f(begin(s)), l(end(s)); 
    static rule<It, A()> const p = strict_double | int_; 

    A a; 
    assert(parse(f,l,p,a)); 

    return a; 
} 

int main() 
{ 
    assert(0 == parse("42").which()); 
    assert(0 == parse("-42").which()); 
    assert(0 == parse("+42").which()); 

    assert(1 == parse("42.").which()); 
    assert(1 == parse("0.").which()); 
    assert(1 == parse(".0").which()); 
    assert(1 == parse("0.0").which()); 
    assert(1 == parse("1e1").which()); 
    assert(1 == parse("1e+1").which()); 
    assert(1 == parse("1e-1").which()); 
    assert(1 == parse("-1e1").which()); 
    assert(1 == parse("-1e+1").which()); 
    assert(1 == parse("-1e-1").which()); 
} 
+0

這是可能的,我不明白這個問題的方案,但不會'數= double_ | int_'只是工作? – 2012-11-07 11:59:30

+0

@sehe,非常感謝,它像一個魅力。 –

+1

@llonesmiz是的,real_parser >()| int_也可以正常工作。 –