2013-01-11 85 views
1

我有以下問題:我重複使用real_p分析器解析實數的舊代碼。我想捕獲每個數字,將其轉換爲字符串,並將其放入字符串向量中。 我正在使用以下代碼,其中l_double是double類型的變量,convertdouble函數將double轉換爲字符串,並且result.m_literalValues是字符串的向量。 但是,代碼不會將分析的值分配給l_double。Spirit Boost real_p分析器行爲奇怪

rule<> alternative3 = +(real_p  [assign_a(l_double)] 
             [push_back_a(result.m_LiteralValues, convertdouble(l_double))] 
             >> str_p(",") 
          ) 

有沒有人有一個想法我做錯了什麼?

注意:我不會重新設計舊代碼,這比給出的示例複雜得多。我只想提取所有解析值的字符串,並將它們放入字符串的向量中。

回答

1

該問題似乎位於push_back_a(result.m_LiteralValues, convertdouble(l_double)),特別是在convertdouble(l_double)push_back_a requires它的第二個參數是存儲在「策略持有者參與者」中的引用,所以使用函數調用會導致錯誤。如果您不需要存儲l_double並且只是將其用作臨時目錄,則完成所需操作的一種方法是創建自己的鳳凰功能,該功能的行爲與的行爲相同,如here(完整示例here)所示。 你定義鳳功能是這樣的:

struct push_back_impl 
{ 
    template <typename Container, typename Item> 
    struct result 
    { 
     typedef void type; 
    }; 

    template <typename Container, typename Item> 
    void operator()(Container& c, Item const& item) const 
    { 
     c.push_back(convertdouble(item)); 
    } 
}; 

function<push_back_impl> const push_back = push_back_impl(); 

,然後定義規則是這樣的:

rule<> alternative3 = +(real_p[push_back(var(result.m_LiteralValues),arg1)] >> str_p(",")); 

完全編譯代碼(改變for循環來顯示結果,如果你不能/唐不想使用c + + 11):

#include <boost/spirit/include/classic_core.hpp> 
#include <boost/spirit/include/classic_operators.hpp> 
#include <boost/spirit/include/phoenix1_functions.hpp> 
#include <boost/spirit/include/phoenix1_primitives.hpp> 
#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 

using namespace boost::spirit::classic; 
using namespace phoenix; 

std::string convertdouble(const double& d) 
{ 
    std::stringstream ss; 
    ss<<d; 
    return ss.str(); 
} 

struct push_back_impl 
{ 
    template <typename Container, typename Item> 
    struct result 
    { 
     typedef void type; 
    }; 

    template <typename Container, typename Item> 
    void operator()(Container& c, Item const& item) const 
    { 
     c.push_back(convertdouble(item)); 
    } 
}; 

function<push_back_impl> const push_back = push_back_impl(); 

struct Results 
{ 
    std::vector<std::string> m_LiteralValues; 
}; 


int main() 
{ 
    Results result; 
    char const* test="2.5,3.6,4.8,"; 
    rule<> alternative3 = +(real_p[push_back(var(result.m_LiteralValues),arg1)] >> str_p(",")); 

    if(parse(test,alternative3,space_p).full) 
    { 
     std::cout << "success" << std::endl; 
     for(auto& str :result.m_LiteralValues) 
      std::cout << str << std::endl; 
    } 
    else 
    { 
     std::cout << "failure" << std::endl; 
    } 

    return 0;      
} 
+0

是的,這解決了這個問題。 –