簡體   English   中英

BOOST_FUSION_ADAPT_STRUCT 使用帶有 std::vector 的遞歸結構<self_type>成員</self_type>

[英]BOOST_FUSION_ADAPT_STRUCT using a recursive struct with a std::vector<self_type> member

我正在嘗試為 spirit x3 解析器聲明遞歸 AST。 解析器語法正在運行,並且由於建議避免語義操作,我正在嘗試改編Rexpr 官方文檔示例

在主文檔中,解析的結構可以用 map 表示,其中鍵是字符串,值是字符串或另一個 map。

在我的例子中,被解析的結構是一個簡單的 n-ary 樹,我希望我能用遞歸結構和forward_ast解決問題:

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

#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

namespace ast
{
  struct node
  {
    std::string name;
    double length;
    std::vector<boost::spirit::x3::forward_ast<node>> children;
  };
}  
BOOST_FUSION_ADAPT_STRUCT(ast::node, name, length, children)

但是我沒有成功編譯 - boost fusion 告訴我

error: explicit specialization of undeclared template struct 'tag_of'
BOOST_FUSION_ADAPT_STRUCT(ast::node, name, length, children)

所以我想我也不明白:

  • 遞歸ast的邏輯,
  • 用於告訴 boost fusion 有關此嵌套類型的語法?
  • 或兩者?

我不確定我是否解決了這個問題,但這也許有幫助:

在編譯器資源管理器上運行

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

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <iostream>

namespace ast {
    using boost::spirit::x3::forward_ast;
    struct node {
        std::string                    name;
        double                         length;
        std::vector<forward_ast<node>> children;
    };

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(ast::node, name, length, children)

namespace ast {
    using boost::fusion::operator<<;
    static inline std::ostream& operator<<(std::ostream& os, std::vector<forward_ast<node>> const& nn) {
        os << "[";
        auto sep = "";
        for (auto& n : nn)
            os << std::exchange(sep, ", ") << n.get();
        return os << "]";
    }
} // namespace ast

int main() {
    ast::node n{
        "demo",
        42,
        {
            ast::node{"nested1", 43, {}},
            ast::node{"nested4",
                      47,
                      {
                          ast::node{"nested2", 45, {}},
                          ast::node{"nested3", 46, {}},
                      }},
            ast::node{"nested5", 48, {}},
        },
    };

    std::cout << "No problem: " << n << "\n";
}

印刷

No problem: (demo 42 [(nested1 43 []), (nested4 47 [(nested2 45 []), (nested3 46 [])]), (nested5 48 [])])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM