Colin
Colin

Reputation: 3762

How to create a function that takes an xexpression OR a container?

I'm a bit lost in xtensor types. I want to create a function that can accept either an expression or a container. How do I do that?

i.e.:

auto multbytwo(WHATGOESHERE x) {
    return x * 2;
}

xt::xtensor<double, 2> a = whatever;
auto b = a + 3.0;
auto c = multbytwo(b);
// now c should NOT be a container, it should be an un-evaluated xexpression.

...and like I said, I'd like the multbytwo function to work correctly if it's argument is an evaluated container, or an 'unevaluated' xexpression. Is it even possible? I'd like to pass the expression WITHOUT evaluation into a temporary, if the argument is an expression. My understanding is that if WHATEVER is xtensor then it will evaluate the expression, and I don't want that.

Upvotes: 0

Views: 181

Answers (1)

johan mabille
johan mabille

Reputation: 424

Each expression type E (xarray, xfunction, etc) inherits from xexpression<E>. Therefore, you can make multbytwo a template function accepting this type, and downcast the argument before using it:

template <class E>
auto multbytwo(const xt::xexpression<E>& x)
{
    return x.derived_cast() * 2;
}

Upvotes: 0

Related Questions