feat(math): introduce best shape trait
This commit is contained in:
@@ -12,6 +12,16 @@ namespace cenet {
|
||||
namespace math {
|
||||
namespace ops {
|
||||
|
||||
namespace detail {
|
||||
|
||||
template <typename T, typename = void>
|
||||
struct has_shape : std::false_type {};
|
||||
|
||||
template <typename T>
|
||||
struct has_shape<T, std::void_t<decltype(std::declval<T>().shape())>> : std::true_type {};
|
||||
|
||||
} // namespace detail
|
||||
|
||||
template <typename Op>
|
||||
struct generic_binary_op {
|
||||
template <typename L, typename R>
|
||||
@@ -26,8 +36,9 @@ struct generic_binary_op {
|
||||
template <typename L, typename R>
|
||||
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<decltype(lhs.shape())>) {
|
||||
using best_shape = cenet::math::detail::best_shape<decltype(shape_wrapper(lhs)), decltype(shape_wrapper(rhs))>;
|
||||
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 <typename T>
|
||||
static constexpr auto shape_wrapper(T&& fwd) {
|
||||
if constexpr (detail::has_shape<T>::value) {
|
||||
return std::forward<T>(fwd).shape();
|
||||
} else {
|
||||
return std::forward<T>(fwd);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct plus : generic_binary_op<std::plus<>> {};
|
||||
|
||||
Reference in New Issue
Block a user