From 0eeafe31c4b56bb36afbd68b0de62fb9fa86a349 Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Sun, 1 Nov 2026 06:48:02 +0100 Subject: [PATCH] feat(math): introduce best shape trait --- include/cenet/math/ops.hpp | 24 +++++++++++++++-- include/cenet/math/tensor_shape.hpp | 41 +++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/include/cenet/math/ops.hpp b/include/cenet/math/ops.hpp index 72b637b..3021f36 100644 --- a/include/cenet/math/ops.hpp +++ b/include/cenet/math/ops.hpp @@ -12,6 +12,16 @@ namespace cenet { namespace math { namespace ops { +namespace detail { + +template +struct has_shape : std::false_type {}; + +template +struct has_shape().shape())>> : std::true_type {}; + +} // namespace detail + template struct generic_binary_op { template @@ -26,8 +36,9 @@ struct generic_binary_op { template static constexpr auto shape(const L& lhs, const R& rhs) { if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands"); - // TODO: introduce "best shape" function/trait - if constexpr (detail::is_static_shape_v) { + using best_shape = cenet::math::detail::best_shape; + static_assert(best_shape::valid, "uncompatible operands"); + if constexpr (best_shape::left) { return lhs.shape(); } else { return rhs.shape(); @@ -44,6 +55,15 @@ struct generic_binary_op { return Op{}(lhs.coeff(index), rhs.coeff(index)); } } +private: + template + static constexpr auto shape_wrapper(T&& fwd) { + if constexpr (detail::has_shape::value) { + return std::forward(fwd).shape(); + } else { + return std::forward(fwd); + } + } }; struct plus : generic_binary_op> {}; diff --git a/include/cenet/math/tensor_shape.hpp b/include/cenet/math/tensor_shape.hpp index 1e65b80..42b0a30 100644 --- a/include/cenet/math/tensor_shape.hpp +++ b/include/cenet/math/tensor_shape.hpp @@ -40,6 +40,8 @@ struct static_shape : shape { constexpr auto get() const { return get_impl::value; } + + static constexpr auto score = sizeof...(Dims); private: template struct compatible_impl : std::false_type {}; @@ -105,6 +107,16 @@ private: struct get_impl<0, First, Rest...> { static constexpr auto value = First; }; + + template + struct score_impl { + static constexpr auto value = Score; + }; + + template + struct score_impl : score_impl {}; +public: + static constexpr auto score = score_impl<0, Dims...>::value; }; namespace detail { @@ -144,6 +156,35 @@ struct is_shape_equivalent, R> template