Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. template <class T, int N>
  4. class MyVector {
  5.     public:
  6.         T operator[](int i) const {
  7.             return data[i];
  8.         }
  9.  
  10.         void setElement(int i, T value) {
  11.             data[i] = value;
  12.         }
  13.  
  14.         private:
  15.         T data[N];
  16. };
  17.  
  18. template <int N, int I>
  19. struct dot {
  20.     static const int loopFlag = (I < N - 1) ? 1 : 0;
  21.  
  22.     template <typename Expr1, typename Expr2>
  23.     static inline int f(const Expr1& a, const Expr2& b) {
  24.         return (a[I] * b[I]) + dot<loopFlag * N, loopFlag * (I + 1)>::f(a, b);
  25.     }
  26. };
  27.  
  28. template <>
  29. struct dot<0, 0> {
  30.     template <typename Expr1, typename Expr2>
  31.     static inline int f(const Expr1& a, const Expr2& b) {
  32.         return 0;
  33.     }
  34. };
  35.  
  36. int main() {
  37.     MyVector<int, 3> vec1;
  38.     MyVector<int, 3> vec2;
  39.     vec1.setElement(0, 5);
  40.     vec1.setElement(1, 7);
  41.     vec1.setElement(2, 8);
  42.     vec2.setElement(0, 13);
  43.     vec2.setElement(1, -4);
  44.     vec2.setElement(2, 17);
  45.     printf("%d\n", dot<3, 0>::f(vec1, vec2));
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement