From a264009629e5c4ec303e8dcea5a4d45598658ada Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Sun, 1 Nov 2026 11:17:44 +0100 Subject: [PATCH] fix(math): fix tensor and tensor_view --- include/cenet/math/tensor.hpp | 18 +++++++++++++++--- include/cenet/math/tensor_view.hpp | 12 ++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/include/cenet/math/tensor.hpp b/include/cenet/math/tensor.hpp index e8efbc3..fb1d9e7 100644 --- a/include/cenet/math/tensor.hpp +++ b/include/cenet/math/tensor.hpp @@ -75,7 +75,7 @@ public: tensor(const tensor& other) : m_shape(other.m_shape) { dyn_alloc(std::make_index_sequence{}); - dyn_copy(std::make_index_sequence{}); + dyn_copy(other.m_items, std::make_index_sequence{}); } tensor& operator=(const tensor& other) { @@ -178,6 +178,16 @@ public: explicit operator view_type() { return view(); } explicit operator constant_view_type() const { return view(); } +public: + template >> + decltype(auto) operator[](Off off) { + return view()[off]; + } + + template >> + decltype(auto) operator[](Off off) const { + return view()[off]; + } public: template void dyn_alloc(std::index_sequence) { - m_items = new value_type[(m_shape.dimensions[Is] * ...)]; + if constexpr (traits::dynamic) { + m_items = new value_type[size()]; + } } template void dyn_copy(const value_type* src, std::index_sequence) { - std::memcpy(m_items, src, sizeof(*m_items) * (m_shape.dimensions[Is] * ... * 1)); + std::memcpy(m_items, src, sizeof(*m_items) * size()); } void release() { diff --git a/include/cenet/math/tensor_view.hpp b/include/cenet/math/tensor_view.hpp index adb7148..e4281b7 100644 --- a/include/cenet/math/tensor_view.hpp +++ b/include/cenet/math/tensor_view.hpp @@ -33,8 +33,10 @@ public: sizeof...(Offs) > 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v && ...))>> decltype(auto) slice(Offs... offs) { auto* ptr = m_view + calculate_offset(std::make_tuple(offs...)); - if constexpr (sizeof...(Offs) == sizeof...(Dims)) return *ptr; - return inner_view(ptr, std::index_sequence{}); + if constexpr (sizeof...(Offs) == sizeof...(Dims)) + return *ptr; + else + return inner_view(ptr, std::index_sequence{}); } template 0 && sizeof...(Offs) <= sizeof...(Dims) && (std::is_integral_v && ...))>> decltype(auto) slice(Offs... offs) const { const auto* ptr = m_view + calculate_offset(std::make_tuple(offs...)); - if constexpr (sizeof...(Offs) == sizeof...(Dims)) return *ptr; - return inner_view(ptr, std::index_sequence{}); + if constexpr (sizeof...(Offs) == sizeof...(Dims)) + return *ptr; + else + return inner_view(ptr, std::index_sequence{}); } public: template >>