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::xsharable_expression< xscalar< CT > >, xt::xsharable_expression< xgenerator< F, R, S > >, xt::xsharable_expression< xbroadcast< CT, X > >, xt::xsharable_expression< xreducer< F, CT, X, O > >, xt::xsharable_expression< xrepeat< CT, R > >, xt::xsharable_expression< xfunction< F, CT… > >, xt::xsharable_expression< D >

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.
}

Downcast functions

inline explicit xshared_expression(const std::shared_ptr<E> &ptr)

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

See also

make_xshared

Parameters:

ptr – shared ptr that contains the expression

inline long use_count() const noexcept

Return the number of times this expression is referenced.

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

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

Helper function to create shared expression from any xexpression.

Parameters:

expr – rvalue expression that will be shared

Returns:

xshared expression

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

Helper function to create shared expression from any xexpression.

See also

make_xshared

Parameters:

expr – rvalue expression that will be shared

Returns:

xshared expression

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

Helper function to create shared expression from any xexpression.

See also

make_xshared

Parameters:

expr – rvalue expression that will be shared

Returns:

xshared expression