问题描述
我有以下 AST 实现,使用 C++17 的 std::variant
类型构建,我想在其上递归应用访问者。我是在 Boost 的 Hana 库中的一些实用程序的帮助下完成的。
#include <iostream>
#include <memory>
#include <variant>
#include <boost/hana.hpp>
namespace hana = boost::hana;
struct AddExpr;
struct SubExpr;
struct MulExpr;
struct divexpr;
using Expr = std::variant<int,AddExpr,SubExpr,MulExpr,divexpr>;
struct BinaryExpr
{
BinaryExpr(std::unique_ptr<Expr> lhs,std::unique_ptr<Expr> rhs) noexcept
: lhs{ std::move(lhs) },rhs{ std::move(rhs) } { }
std::unique_ptr<Expr> lhs;
std::unique_ptr<Expr> rhs;
};
struct AddExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct SubExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct MulExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct divexpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
int main()
{
Expr root {
MulExpr{
std::make_unique<Expr>(AddExpr{
std::make_unique<Expr>(1),std::make_unique<Expr>(2),}),std::make_unique<Expr>(SubExpr{
std::make_unique<Expr>(3),std::make_unique<Expr>(4),}
};
constexpr auto printer = hana::fix([](auto visitor,auto const& arg) -> void {
hana::overload(
[&](int val) {
std::cout << val;
},[&](AddExpr const& exp) {
std::cout << "(";
std::visit(visitor,*exp.lhs);
std::cout << "+";
std::visit(visitor,*exp.rhs);
std::cout << ")";
},[&](SubExpr const& exp) {
std::cout << "(";
std::visit(visitor,*exp.lhs);
std::cout << "-";
std::visit(visitor,[&](MulExpr const& exp) {
std::cout << "(";
std::visit(visitor,*exp.lhs);
std::cout << "*";
std::visit(visitor,[&](divexpr const& exp) {
std::cout << "(";
std::visit(visitor,*exp.lhs);
std::cout << "/";
std::visit(visitor,*exp.rhs);
std::cout << ")";
}
)(arg);
});
std::visit(printer,root);
std::cout << "\n";
return 0;
}
使用 GCC 7.1+ 时代码编译时没有任何警告,但 Clang 似乎无法编译它,而是发出以下错误。
<source>:54:22: error: function 'visit<boost::hana::fix_t<(lambda at <source>:47:40)> &,std::variant<int,divexpr> &>' with deduced return type cannot be used before it is defined
std::visit(visitor,*exp.lhs);
...
这是 Clang 中的错误吗?或者我做错了什么,如果是这样,为什么这对 GCC 有效?
另外,有没有一种优雅的方式可以在 Clang 中做我想做的事?特别是,我希望能够从一些重载的 lambda 表达式创建 printer
访问者,而不是必须创建一个 PrinterVisitor
类,其中 operator()
为每种类型重载。但是,如果这是不可能的,我愿意接受其他建议。
解决方法
您的确切代码也不适用于 GCC 主干:Compiler Explorero,自发布以来这很有趣 确实有效:Compiler Explorer。
我的本地消息非常相似:GCC
/home/sehe/custom/boost_1_75_0/boost/hana/functional/fix.hpp|74 col 19| error: use of ‘main()::<lambda(auto:39,const auto:40&)> [with auto:39 = boost::hana::fix_t<main()::<lambda(auto:39,const auto:40&)> >; auto:40 = int]’ before deduction of ‘auto’
|| 74 | { return f(fix(f),static_cast<X&&>(x)...); }
铿锵:
/home/sehe/custom/boost_1_75_0/boost/hana/functional/fix.hpp|74 col 18| error: function 'operator()<boost::hana::fix_t<(lambda at /home/sehe/Projects/stackoverflow/test.cpp:44:40)>,int>' with deduced return type cannot be used before it is defined
|| { return f(fix(f),static_cast<X&&>(x)...); }
我记得当我编写自己的组合器时,我无法绕过实现助手,例如:
struct F {
template <typename Self,typename T>
void operator()(Self const& self,T const& arg) const {
auto bin = [&](char op,BinaryExpr const& exp) {
std::cout << "("; std::visit(self,*exp.lhs); std::cout << op; std::visit(self,*exp.rhs); std::cout << ")";
};
hana::overload(
[&](int val) { std::cout << val; },[&](AddExpr const& exp) { bin('+',exp); },[&](SubExpr const& exp) { bin('-',[&](MulExpr const& exp) { bin('*',[&](DivExpr const& exp) { bin('/',exp); }
)(arg);
}
};
说明
我认为它只需要默认的可构造 lambdas,这是 C++20 的新内容:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0624r2.pdf
来源:https://www.bfilipek.com/2019/03/lambdas-story-part2.html
使用 C++20,我们将获得以下功能:
- 允许 [=,this] 作为 lambda 捕获 - P0409R2 并通过 [=] 弃用隐式捕获 - P0806
- lambda init-capture 中的包扩展:...args = std::move(args)](){} - P0780
- 结构化绑定的静态、thread_local 和 lambda 捕获 - P1091
- 模板 lambda(也包含概念)- P0428R2
- 简化隐式 lambda 捕获 - P0588R1
- 默认可构造和可分配的无状态 lambda - P0624R2
- 未评估上下文中的 Lambda - P0315R4
这让我相信它可以在 c++20 中工作。
还价
对于递归访问者,我有一些简化和我喜欢的模式。有一些好处,比如
- 封装[递归]访问
- 更容易绑定额外的参数(在本例中为
std::cout
)
我发现可维护性比在调用站点上声明访问者更方便。
编辑我找到了一个更有说服力的解决方案,所以我会放一个链接,以防您感兴趣:Live On Compiler Explorer
有你的蛋糕,吃它,没有升压
我意识到您可以拥有蛋糕并吃掉它,而根本不需要任何 Boost:
template <typename... F>
struct RecursiveVisitor : F... {
template <typename... Ts>
void operator()(std::variant<Ts...> const& v) const {
std::visit( std::bind(*this,std::cref(*this),std::placeholders::_1),v );
}
using F::operator()...;
};
template <typename... F>
RecursiveVisitor(F...) -> RecursiveVisitor<F...>;
现在您可以通过以下方式完成您的任务:
RecursiveVisitor const printer {
[](auto const&,int const& v) { std::cout << v; },[](auto const& self,AddExpr const& exp) { self(self,'+',SubExpr const& exp) { self(self,'-',MulExpr const& exp) { self(self,'*',DivExpr const& exp) { self(self,'/',char op,BinaryExpr const& exp) {
std::cout << "(";
self(*exp.lhs);
std::cout << op;
self(*exp.rhs);
std::cout << ")";
}
};
哪些是全面有效的:
#include <iostream>
#include <memory>
#include <variant>
#include <functional>
struct AddExpr;
struct SubExpr;
struct MulExpr;
struct DivExpr;
using Expr = std::variant<int,AddExpr,SubExpr,MulExpr,DivExpr>;
struct BinaryExpr
{
BinaryExpr(Expr l,Expr r);
BinaryExpr(BinaryExpr const& o);
std::unique_ptr<Expr> lhs,rhs;
};
struct AddExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct SubExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct MulExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct DivExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
BinaryExpr::BinaryExpr(Expr l,Expr r)
: lhs{ std::make_unique<Expr>(l) },rhs{ std::make_unique<Expr>(r) } { }
BinaryExpr::BinaryExpr(BinaryExpr const& o)
: lhs{ std::make_unique<Expr>(*o.lhs) },rhs{ std::make_unique<Expr>(*o.rhs) } { }
template <typename... F>
struct RecursiveVisitor : F... {
template <typename... Ts>
void operator()(std::variant<Ts...> const& v) const {
std::visit( std::bind(*this,v );
}
using F::operator()...;
};
template <typename... F>
RecursiveVisitor(F...) -> RecursiveVisitor<F...>;
int main()
{
RecursiveVisitor const printer {
[](auto const&,BinaryExpr const& exp) {
std::cout << "(";
self(*exp.lhs);
std::cout << op;
self(*exp.rhs);
std::cout << ")";
}
};
for (Expr root : { Expr
{ MulExpr{ AddExpr{ 1,2 },SubExpr{ 3,4 } } },{ DivExpr{ 1,MulExpr{ 7,4 } } } },})
{
printer(root);
std::cout << "\n";
}
}
打印
((1+2)*(3-4))
(1/(7*(3-4)))
我意识到这会手动复制 Y 组合器模式,但至少它消除了所有瓶颈。此外,共享 char,BinExpr&
重载并不是如何优雅地“只是另一个重载”。
@sehe 发布的 solution 中的最后一个例子几乎是完美的,除了内存分配的数量随着表达式树的深度呈指数增长。这是因为复制构造函数被调用了 2^l + 2^r
次,其中 l
和 r
分别是左右表达式树的深度,传递给 BinaryExpr
的构造函数.
因此,为了构建以下表达式树,我发现需要 68 次分配。
Expr root {
AddExpr {
MulExpr{ AddExpr{ 1,4 } },DivExpr{ SubExpr{ 5,6 },AddExpr{ 7,8 } },}
};
但是,我们可以通过像这样移动(而不是复制)表达式树来轻松避免这些内存分配。
struct AddExpr;
struct SubExpr;
struct MulExpr;
struct DivExpr;
using Expr = std::variant<int,DivExpr>;
struct BinaryExpr
{
BinaryExpr(Expr lhs,Expr rhs) noexcept;
BinaryExpr(BinaryExpr&&) = default; // Require the default move-constructor.
BinaryExpr(BinaryExpr const&);
std::unique_ptr<Expr> lhs;
std::unique_ptr<Expr> rhs;
};
struct AddExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct SubExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct MulExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
struct DivExpr : BinaryExpr { using BinaryExpr::BinaryExpr; };
BinaryExpr::BinaryExpr(Expr lhs,Expr rhs) noexcept
: lhs{ std::make_unique<Expr>(std::move(lhs)) },// Call std::move() here.
rhs{ std::make_unique<Expr>(std::move(rhs)) } // Call std::move() here.
{ }
BinaryExpr::BinaryExpr(BinaryExpr const& exp)
: lhs{ std::make_unique<Expr>(*exp.lhs) },rhs{ std::make_unique<Expr>(*exp.rhs) }
{ }
通过此修改,构建如上所示的示例表达式树只需要 14 次分配,而不是 68 次。