PrevUpHomeNext

Expressions

Boost.YAP consists of expressions and functions that operate on them. A function that takes an expression will accept any type that models the Expression concept.

For a type T to model the Expression concept, T must contain at least an expr_kind (terminal, plus-operation, etc.) and a boost::hana::tuple<> of values. That's it.

[Note] Note

The boost::hana::tuple<> of values is constrained, based on the kind of the expression; see the full Expression documentation for details.

Here's an example of an expression:

template <boost::yap::expr_kind Kind, typename Tuple>
struct minimal_expr
{
    static const boost::yap::expr_kind kind = Kind;

    Tuple elements;
};

That's a template that models ExpressionTemplate. Instantiated with the proper template parameters, it produces Expressions.

Ok, so it's not that interesting by itself — minimal_expr has no operations defined for it. But we can still use it with the Boost.YAP functions that take an Expression. Let's make a Boost.YAP plus-expression manually:

auto left = boost::yap::make_terminal<minimal_expr>(1);
auto right = boost::yap::make_terminal<minimal_expr>(41);

auto expr = boost::yap::make_expression<
    minimal_expr,
    boost::yap::expr_kind::plus
>(left, right);

If we evaluate it using evaluate(), it does what you would expect:

auto result = boost::yap::evaluate(expr);

std::cout << result << "\n"; // prints "42"

One more thing. It is important to remember that Boost.YAP expressions are all-lazy, all the time. There is no auto-evaluation of a Boost.YAP expression like there is with normal C++ expressions. If you want your expressions to be evaluated, you must call evaluate(), or define non-lazy operations that force evaluation where and when you want it. This last approach is usually the right one, and there are lots of examples of how to do this in the Examples section. In particular, checkout the Lazy Vector and TArray examples.


PrevUpHomeNext