m-tosch / mu

A small, simple c++ math library
MIT License
1 stars 0 forks source link

clean dot() function setup #66

Closed m-tosch closed 3 years ago

m-tosch commented 3 years ago

Vector member function dot() contains some ugly code to make it work conveniently for different and same typed Vectors

template <typename U = void, std::size_t N2, typename T2>
std::conditional_t<std::is_same_v<U, void>, T, U> dot(
    const Vector<N2, T2> &other) const {
  static_assert(N == N2, "Vector size mismatch");
  if constexpr (!std::is_same_v<T, T2>) {
    static_assert(!std::is_same_v<U, void>,
                  "Vector types are different. please specify the return type. e.g. \"dot<float>(vec1, vec2);\"");
  }
  using U_ = std::conditional_t<std::is_same_v<U, void>, T, U>;
  U_ ret{};
  for (std::size_t i = 0; i < N; i++) {
    ret += data_[i] * other[i];
  }
  return ret;
}

maybe the code can be cleaned up a little bit. maybe the static asserts can become SFINAE code ?

m-tosch commented 3 years ago

also concerns matrix dot() functions

m-tosch commented 3 years ago

the if constexpr() { ... } part of the code is c++17

Update replaced by using std::conditional and a static_assert in #96 new code

template <typename U = void, std::size_t N2, typename T2>
std::conditional_t<std::is_same<U, void>::value, T, U> dot(
    const Vector<N2, T2> &rhs) const {
  static_assert(N == N2, "Vector size mismatch");
  /* if the two types are not the same, use U which must not be void */
  using cond1 = std::conditional_t<!std::is_same<T, T2>::value, U, T>;
  static_assert(!std::is_same<cond1, void>::value,
                "Vector types are different. please specify the return "
                "type. e.g. \"vec1.dot<float>(vec2);\"");
  using U_ = std::conditional_t<std::is_same<U, void>::value, T, U>;
  U_ ret{};
  for (std::size_t i = 0; i < N; i++) {
    ret += data_[i] * rhs[i];
  }
  return ret;
}

could still use some clean up!

m-tosch commented 3 years ago

removed cond1 and used U_ in the static_assert directly (see commit below)