gpt4 book ai didi

c++ - 用精神解析成类?

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:55 25 4
gpt4 key购买 nike

下面是 boost spirit 文档中的 employee.cpp 源文件。它是“struct employee”,后跟一个告诉融合有关“struct employee”的宏,然后是 employee 解析器。

我正在尝试根据我的目的对此进行调整,但我没有使用“struct employee”,而是想使用一些类来代替“struct employee”。

我正在考虑尝试用类替换“struct employee”,但我没有看到在融合中执行此操作的宏?我不想把它放在结构中的原因是因为我必须将它从结构复制到我的类中,这似乎是不必要的,更不用说性能影响了。

在仔细考虑之后,我可能不理解 Fusion 和元组的用途,因此,也许我必须那样使用它,然后将数据移动到我自己的类结构中。

有什么指导吗?

namespace client { namespace ast
{
///////////////////////////////////////////////////////////////////////////
// Our employee struct
///////////////////////////////////////////////////////////////////////////
struct employee
{
int age;
std::string surname;
std::string forename;
double salary;
};

using boost::fusion::operator<<;
}}

// We need to tell fusion about our employee struct
// to make it a first-class fusion citizen. This has to
// be in global scope.

BOOST_FUSION_ADAPT_STRUCT(
client::ast::employee,
(int, age)
(std::string, surname)
(std::string, forename)
(double, salary)
)

namespace client
{
///////////////////////////////////////////////////////////////////////////////
// Our employee parser
///////////////////////////////////////////////////////////////////////////////
namespace parser
{
namespace x3 = boost::spirit::x3;
namespace ascii = boost::spirit::x3::ascii;

using x3::int_;
using x3::lit;
using x3::double_;
using x3::lexeme;
using ascii::char_;

x3::rule<class employee, ast::employee> const employee = "employee";

auto const quoted_string = lexeme['"' >> +(char_ - '"') >> '"'];

auto const employee_def =
lit("employee")
>> '{'
>> int_ >> ','
>> quoted_string >> ','
>> quoted_string >> ','
>> double_
>> '}'
;

BOOST_SPIRIT_DEFINE(employee);
}
}

最佳答案

struct之间没有区别和 class ¹.

除此之外,人们通常的意思是“我想要没有直接数据成员(“字段”)访问的类”。

现在我可以直接指向您 BOOST_FUSION_ADAPT_ADT .这就是您要寻找的。

但是

这意味着您无论如何都为所有数据成员公开了 setter。这是一个巨大的反模式²,因为它只会导致准类³。

考虑使用工厂函数(使用 Phoenix 来调整它们以从语义操作中调用//但请参阅 Boost Spirit: "Semantic actions are evil"? )或者,确实有一个干净的 AST 表示,您然后使用它来构建域对象图来自。

如果您负担不起(因为拷贝),那么您就真的买不起 Spirit V2 IMO。 Spirit 旨在快速开发/原型(prototype)化(更改)语法,同时不会生成糟糕的代码。但是,如果您买不起拷贝,那么是时候手动滚动您的解析器了(或转移到 Spirit X3)


¹ 从字面上看,唯一的区别是 struct默认公开所有成员,但您仍然可以使用 private:protected:

² 可能起源于 Java 的 PoJo 或“Bean”的历史

³ "Pseudo-Classes and Quasi-ClassesConfuse Object-Oriented Programming"

关于c++ - 用精神解析成类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44581141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com