2016-11-08 69 views
1

我想解析一些輸入,如longstd::string(如果引用)。對此的合理解決方案是使用x3::variant<long, std::string>來存儲數據。下面是一個簡單的程序:Boost Spirit X3:將數據提取到x3 ::變體<...>始終爲空

#include <iostream> 
#include <string> 

#include <boost/spirit/home/x3.hpp> 
#include <boost/spirit/home/x3/support/ast/variant.hpp> 

namespace x3 = boost::spirit::x3; 

const x3::rule<class number_tag, long> number = "number"; 
const auto number_def = x3::long_; 
BOOST_SPIRIT_DEFINE(number); 

const x3::rule<class string_tag, std::string> string = "string"; 
const auto string_def = x3::lexeme['"' >> *(x3::char_ - '"') >> '"']; 
BOOST_SPIRIT_DEFINE(string); 

using any_type = x3::variant<long, std::string>; 
const x3::rule<class any_tag, any_type> any = "any"; 
const auto any_def = number | string; 
BOOST_SPIRIT_DEFINE(any); 

int main() 
{ 
    const std::string src = "18"; 
    any_type result; 
    auto iter = src.begin(); 
    bool success = x3::phrase_parse(iter, src.end(), any, x3::space, result); 
    if (!success || iter != src.end()) 
     return 1; 
    else 
     std::cout << "Result: " << result << std::endl; 
} 

預期的結果是:

Result: 18 

然而,實際結果很簡單:

Result: 

我在做什麼錯?升級版本是1.61。

回答

1

不能像這樣打印變體。您必須將其傳遞給訪問者。對於如(用於轉換檢查完成沒有太大錯誤):

struct Visitor 
{ 
    using result_type = long; 

    result_type operator()(long v) const { return v; } 
    result_type operator() (const std::string& v) { return std::atol(v.c_str()); } 
}; 

,應該從你的代碼調用,如:

if (!success || iter != src.end()) { 
     return 1; 
    } else { 
     Visitor v; 
     std::cout << "Result: " << boost::apply_visitor(v, result) << std::endl; 
    } 
+0

有趣...'運營商<<'的'正常提升: :變種'只是工作。 –