首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Boost recursive_wrapper递归

Boost recursive_wrapper递归
EN

Stack Overflow用户
提问于 2016-03-09 15:30:30
回答 1查看 715关注 0票数 0

我有一个binop结构,它表示两个相同类型的表达式的二元运算。我有两种不同类型的表达式:定义为boost::variant的arithmetic_exprlogical_expr

我们的目标是让binop有两个字段:rhs和这些表达式的具体类型的lhs。如何做到这一点?

这就是我到目前为止想出来的:

代码语言:javascript
复制
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;
};

一个用例示例是:

代码语言:javascript
复制
(((1 + 2) /* arithmetic_expr */ + 3) /* arithmetic_expr */ AND (4 + 5) /* arithmetic_expr */) /* logical_expr */
EN

回答 1

Stack Overflow用户

发布于 2016-03-09 17:15:18

像这样的东西?

代码语言:javascript
复制
#include <iostream>
#include <utility>
#include <boost/variant.hpp>

// identity evaluation
int evaluate(int i) { return i; }

// introduce the concep of binary op
template<class ActualOp> struct binary_op;

using add = binary_op<std::plus<int>>;
using subtract = binary_op<std::minus<int>>;
using times = binary_op<std::multiplies<int>>;

// our variant
using expression = boost::variant
<
int,
boost::recursive_wrapper<add>,
boost::recursive_wrapper<subtract>,
boost::recursive_wrapper<times>
>;

// overload for evaluating the variant
struct compute : boost::static_visitor<int>
{
    template<class T> int operator()(const T& t) const { return evaluate(t); }
};


int evaluate(const expression& e)
{
    return boost::apply_visitor(compute(), e);
};

// evaluate the binary op
template<class ActualOp>
struct binary_op
{
    binary_op(expression l, expression r)
    : _l(std::move(l)), _r(std::move(r))
    {}

    ActualOp _op;
    expression _l, _r;
};
template<class Op>
int evaluate(const binary_op<Op>& o) {
    return o._op(evaluate(o._l), evaluate(o._r));
}

int main()
{
    using namespace std;


    expression e = add(6, times(3,subtract(7,2)));

    cout << evaluate(e) << endl;
    return 0;
}

预期输出:

代码语言:javascript
复制
21
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35885517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档