xtensor - Tensor wrapper raises trivial_assigner error during runtime

164 Views Asked by At

I'm currently using xtensor for an application, and I wanted to wrap over the tensors to make a class called BitArray.

#include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xview.hpp"
#include "xtensor/xindex_view.hpp"

xt::xarray<double> arr {1, 2, 3};

template <typename E>
class BitArray{
public:
    BitArray(const xt::xexpression<E>& _array, float _alpha) :
        b(xt::cast<std::int8_t>(_array.derived_cast())), alpha(_alpha) {}
    xt::xarray<E> b;
    float alpha;
};

template <class E>
auto make_bitarray(xt::xexpression<E>& expr, float alpha)
{
    return BitArray<E>(expr, alpha);
}

auto a = make_bitarray(arr, 3); // Error

I get the error message below:

Standard Exception: Precondition violation!
Internal error: trivial_assigner called with unrelated types.
  /srv/conda/include/xtensor/xassign.hpp(505)

What does this mean and what can I do to resolve this?

2

There are 2 best solutions below

0
On BEST ANSWER

The slightly better solution would be to create the cast inside your make_bitarray function:

template <typename T>
class BitArray{
public:
    BitArray(T&& _array, float _alpha) :
        b(std::move(_array)), alpha(_alpha)
    {
    }

    T&& b;
    float alpha;
};

template <class T>
auto make_bitarray(const xt::xexpression<T>& expr, float alpha)
{
    auto cast = xt::cast<int8>(expr);
    // need to move temporary here
    return BitArray<decltype(cast)>(std::move(expr), alpha);
}
0
On

This is what I did to provide a wrapper over the complicated template arguments:

template <typename T>
class BitArray{
public:
    BitArray(const xt::xexpression<T>& _array, float _alpha) :
        b(xt::cast<int8>(_array.derived_cast())), alpha(_alpha)
    {
    }

    decltype(xt::cast<int8>(std::declval<std::add_lvalue_reference_t<T>>())) b;
    float alpha;
};

template <class T>
auto make_bitarray(const xt::xexpression<T>& expr, float alpha)
{
    return BitArray<T>(expr, alpha);
}

Add an lvalue because I inspected that the only thing that was missing was a ref, and you need derived_cast in order to have value_type, and then you need to wrap that inside of an xexpression to make sure it can be evaluated, and decltypeing this gives you the answer.