【发布时间】:2016-03-09 07:30:30
【问题描述】:
我有 binop 结构,它表示 2 个相同类型的表达式的二元运算。
我有 2 种不同类型的表达式:arithmetic_expr 和 logical_expr 定义为 boost::variant。
目标是让binop 有两个字段:rhs 和lhs 这些表达式的具体类型。如何做到这一点?
这是我目前想出的:
template <typename expr_type, typename tag> struct binop;
struct op_plus {};
typedef boost::variant<
int,
boost::recursive_wrapper<binop<arithmetic_expr, op_plus>> // <-- fails here 'arithmetic_expr': undeclared identifier
> arithmetic_expr;
struct op_and {};
typedef boost::variant<
bool,
boost::recursive_wrapper<binop<logical_expr, op_and>>
> logical_expr;
template <typename expr_type, typename tag>
struct binop
{
explicit binop(const expr_type& l, const expr_type& r) : lhs(l), rhs(r) { }
expr_type lhs, rhs;
};
一个用例示例是:
(((1 + 2) /* arithmetic_expr */ + 3) /* arithmetic_expr */ AND (4 + 5) /* arithmetic_expr */) /* logical_expr */
【问题讨论】:
-
我们可以从在某处定义算术表达式开始。我在上面的代码中看不到它的定义。
-
如果我将算术表达式声明为结构,编译器会抱怨变体声明与结构不兼容..
-
您想在变体中存储绑定值,还是只存储操作?即变体是设计成一个完整的表达式还是一个特定领域的语言程序,可以从其他地方获取输入?你能发布一个用例的例子吗?