fork download
  1. #include <cmath>
  2. #include <array>
  3. #include <algorithm>
  4.  
  5. template <typename T, size_t M, size_t N>
  6. class Matrix
  7. {
  8. public:
  9. static const size_t ROWS = M;
  10. static const size_t COLS = N;
  11. typedef T SCALAR;
  12.  
  13. SCALAR operator[](const size_t index) const
  14. {
  15. static_assert((COLS == 1 || ROWS == 1), "operator[] is only for vectors (single row or column).");
  16. return m_elements.at(index);
  17. }
  18.  
  19. SCALAR& operator[](const size_t index)
  20. {
  21. static_assert((COLS == 1 || ROWS == 1), "operator[] is only for vectors (single row or column).");
  22. return m_elements.at(index);
  23. }
  24.  
  25. std::array<T, M * N> m_elements;
  26. };
  27.  
  28. template <typename T, size_t N, size_t M, typename std::enable_if<(M == 1 || N == 1), int>::type = 0>
  29. static inline T Length(
  30. const Matrix<T, N, M> & input)
  31. {
  32. T value = 0;
  33. for (size_t i = 0; i < std::max(N, M); ++i)
  34. {
  35. value += (input[i] * input[i]);
  36. }
  37. return std::sqrt(value);
  38. }
  39. template <typename T, size_t M, size_t N, typename std::enable_if<(M == 3 && N == 1) || (M == 1 && N == 3), int>::type = 0>
  40. static inline Matrix<T, M, N>
  41. CrossProduct(const Matrix<T, M, N> & a, const Matrix<T, M, N> & b)
  42. {
  43. Matrix<T, M, N> result;
  44. result[0] = a[1] * b[2] - a[2] * b[1];
  45. result[1] = a[2] * b[0] - a[0] * b[2];
  46. result[2] = a[0] * b[1] - a[1] * b[0];
  47. return result;
  48. }
  49.  
  50.  
  51. int main()
  52. {
  53. Matrix<double, 1, 1> m11;
  54. Matrix<double, 3, 1> m31;
  55. Matrix<double, 1, 3> m13;
  56. Matrix<double, 3, 3> m33;
  57.  
  58.  
  59. auto l0 = Length(m11); // Should work, but doesn't: no matching function for call to 'Length(Matrix<double, 1, 1>&)'
  60. auto l1 = Length(m31); // Should work, but doesn't: no matching function for call to 'Length(Matrix<double, 3, 1>&)'
  61. auto l2 = Length(m13); // Should work, but doesn't: no matching function for call to 'Length(Matrix<double, 1, 3>&)'
  62. //auto l3 = Length(m33); // Shouldn't work, and doesn't: no matching function for call to 'Length(Matrix<double, 3, 3>&)'
  63. auto v1 = CrossProduct(m13, m13); //Works, as expected
  64. //auto v2 = CrossProduct(m11, m11); // As expected: enable_if.cpp:71:32: error: no matching function for
  65. // call to 'CrossProduct(Matrix<double, 1, 1>&, Matrix<double, 1, 1>&)'
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty