2012-11-14 28 views
2

我有很多具有共同的前綴和後綴規則:分解出精神的公用部分規則

rule = begin_stuff >> some >> other >> stuff >> end_stuff. 

(其中begin_stuffend_stuff從文字組成)

我希望能夠到說

rule = wrapped(some >> other >> stuff); 

我試過的東西沿着

但我所得到的大部分是來自Qi的編譯時間斷言。

我該如何以這種方式重構Spirit規則?

回答

2

我認爲你正在尋找'subrules'(即Spirit V1/classic曾經有過)。現在已經過時了。

看一看

  • C++ 11 autoBOOST_AUTO

    auto subexpression = int_ >> ',' >> double_; 
    qi::rule<It> rule = "A:" >> subexpression >> "Rest:" >> (subexpression % eol); 
    

    過去有問題與精神的規則使用auto(尤其是與MSVC)(見Zero to 60 MPH in 2 seconds!和評論)但我已被告知(很快)is no longer an issue

    Yep. Anyway,FYI, it's fixed in Spirit-3. You can 
    use auto all you want. 
    
    Regards, 
    -- 
    Joel de Guzman 
    
  • qi::lazy

  • inherited arguments - 在Mini XML - ASTs教程

這裏介紹的是概念的證明通過一個共同的子規則不同的「化合物」的規則,以允許在()包裝, []{}

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

namespace qi = boost::spirit::qi; 
namespace phx = boost::phoenix; 

typedef std::string::const_iterator It; 

template <typename R> 
    void test(const std::string& input, R const& rule) 
{ 
    It f(input.begin()), l(input.end()); 
    bool ok = qi::phrase_parse(f,l,rule,qi::space); 
    std::cout << "'" << input << "'\tparse " << (ok?"success":"failure") << "\n"; 
} 

int main() 
{ 
    typedef qi::rule<It,     qi::space_type> common_rule; 
    typedef qi::rule<It, void(common_rule), qi::space_type> compound_rule; 

    common_rule common = qi::int_; 

    compound_rule 
     in_parens = qi::lit('(') >> qi::_r1 >> ')', 
     in_brackets = qi::lit('[') >> qi::_r1 >> ']', 
     in_braces = qi::lit('{') >> qi::_r1 >> '}'; 

    test("{ 231 }" , in_braces (phx::ref(common))); 
    test("{ hello }", in_braces (phx::val("hello"))); 

    test("(231)" , in_parens (phx::ref(common))); 
    test("(hello)", in_parens (phx::val("hello"))); 

    test("[ 231 ]" , in_brackets(phx::ref(common))); 
    test("[ hello ]", in_brackets(phx::val("hello"))); 
} 

輸出:

'{ 231 }' parse success 
'{ hello }' parse success 
'(231)' parse success 
'(hello)' parse success 
'[ 231 ]' parse success 
'[ hello ]' parse success 

PS。注意以上是不是典型的Spirit語法。當「通用」規則會暴露不同的屬性時,這種方式並不會奏效。

+0

謝謝你能回答。你能完成它嗎?最後一個字「也」告訴我,你有更多的話要說... – Arkadiy

+0

@Arkadiy我不記得任何具體的我要說。除了我可能添加的關於「自動」的事情。乾杯 – sehe

+0

問題:我們如何從val(「hello」)到common_rule? – Arkadiy