2015-09-10 40 views
1

具體而言,使用語法g,我該如何解析字符串s?我應該給我什麼論據?我嘗試了很多電話,總是遇到錯誤。如何使用parse/phrase_parse函數

此外,由於我不確定哪一個我稍後會用到,使用phrase_parse會有什麼區別嗎?

namespace qi = boost::spirit::qi; 
int main() { 
    My_grammar<std::string::const_iterator> g; 
    std::string s = "a"; // string to parse 
    if (qi::parse(/*...*/)) { 
     std::cout << "String parsed !"; 
    } else { 
     std::cout << "String doesn't parse !"; 
    } 
    return EXIT_SUCCESS; 
} 

回答

3

基本上,你應該看看教程,但問題的一部分是,你或多或少需要創建一個變量來容納啓動迭代器。因爲,它通過參考qi::parse,並且在哪裏停止可以被認爲是qi::parse函數的輸出。如果您嘗試通過它s.begin()它不會工作,因爲那麼你試圖綁定一個臨時引用。

namespace qi = boost::spirit::qi; 
int main() { 
    My_grammar<std::string::const_iterator> g; 
    std::string s = "a"; // string to parse 
    std::string::const_iterator it = s.begin(); // The type declaration here 
    std::string::const_iterator end = s.end(); // and here needs to match template parameter 
               // which you used to instantiate g 

    if (qi::parse(it, end, g)) { 
     std::cout << "String parsed !"; 
    } else { 
     std::cout << "String doesn't parse !"; 
    } 
    return EXIT_SUCCESS; 
} 

僅當您要明確指定跳過語法時才使用phrase_parse

+0

這給我的幾個錯誤,這成爲第一: 從「布爾的boost ::精神::氣需要: :解析(Iterator&,Iterator,Expr&)[使用Iterator = __gnu_cxx :: __ normal_iterator >; Expr = My_grammar <__ gnu_cxx :: __ normal_iterator >>]' – LogicalKip

+0

我改變了答案,可能'auto'並不是完全推導出'std :: string :: const_iterator',這是上述工作需要。你也沒有把它標記爲C++ 11,所以我不應該使用'auto':X –

2

是的,會有區別。

phrase_parse使用船長並且可能不會消耗所有輸入並仍然返回true。

在所有其他方面,兩者是相同的。你真的應該正好砸在文檔:

std::string::const_iterator f(s.begin(), l(s.end()); 

if (qi::parse(f, l, g/*, optional, bound, attribute, references*/)) 
+0

這些例子只有在飛行語法和phrase_parse(因此我的第二個問題)時,我不確定是否它改變了一切。至於無意義的「Iterator」參數,一旦我查看了示例的完整代碼,我看到它使用了s.begin()和s.end(),因此我也是如此。看來問題實際上是因爲我有將它們聲明爲變量,而不是簡單地給出價值(目前對我有意義)。 – LogicalKip

+0

呵呵。你忘了將這些混亂添加到它似乎的問題上。你是否和克里斯談過這個問題(或者他只是猜測)? – sehe

+0

我剛剛猜到,我想我在開始時犯了類似的錯誤 –