繁体   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