我目前正在为应用程序使用xtensor,我想包装张量以创建一个名为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


我收到以下错误消息:

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


这是什么意思,我该怎么解决?

最佳答案

更好的解决方案是在make_bitarray函数内部创建演员表:

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);
}

09-04 03:22
查看更多