xexpression

Defined in xtensor/xexpression.hpp

template <class D>
class xexpression

Base class for xexpressions.

The xexpression class is the base class for all classes representing an expression that can be evaluated to a multidimensional container with tensor semantic. Functions that can apply to any xexpression regardless of its specific type should take a xexpression argument.

Template Parameters
  • E: The derived type.

Subclassed by xt::xsemantic_base< D >

Downcast functions

auto derived_cast()

Returns a reference to the actual derived type of the xexpression.

Returns a constant reference to the actual derived type of the xexpression.

auto derived_cast() const

Returns a constant reference to the actual derived type of the xexpression.

template <class E>
class xshared_expression : public xt::xexpression<xshared_expression<E>>

Shared xexpressions.

Due to C++ lifetime constraints it’s sometimes necessary to create shared expressions (akin to a shared pointer).

For example, when a temporary expression needs to be used twice in another expression, shared expressions can come to the rescue:

template <class E>
auto cos_plus_sin(xexpression<E>&& expr)
{
    // THIS IS WRONG: forwarding rvalue twice not permitted!
    // return xt::sin(std::forward<E>(expr)) + xt::cos(std::forward<E>(expr));
    // THIS IS WRONG TOO: because second `expr` is taken as reference (which will be invalid)
    // return xt::sin(std::forward<E>(expr)) + xt::cos(expr)
    auto shared_expr = xt::make_xshared(std::forward<E>(expr));
    auto result = xt::sin(shared_expr) + xt::cos(shared_expr);
    std::cout << shared_expr.use_count() << std::endl; // Will print 3 because used twice in expression
    return result; // all valid because expr lifetime managed by xshared_expression / shared_ptr.
}

Public Functions

xshared_expression(std::shared_ptr<E> &&ptr)

Constructor for xshared expression (note: usually the free function make_xshared is recommended).

See
make_xshared
Parameters
  • ptr: shared ptr that contains the expression

long use_count() const

Return the number of times this expression is referenced.

Internally calls the use_count() function of the std::shared_ptr.

template <class E>
auto xt::make_xshared(xexpression<E> &&expr)

Helper function to create shared expression from any xexpression.

Return
xshared expression
Parameters
  • expr: rvalue expression that will be shared