Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- template <class T, int N>
- class MyVector {
- public:
- T operator[](int i) const {
- return data[i];
- }
- void setElement(int i, T value) {
- data[i] = value;
- }
- private:
- T data[N];
- };
- template <int N, int I>
- struct sum {
- static const int loopFlag = (I < N - 1) ? 1 : 0;
- template <typename Expr>
- static inline double f(const Expr& vec) {
- return ((double)vec[I] / N) + sum<loopFlag * N, loopFlag * (I + 1)>::f(vec);
- }
- };
- template <>
- struct sum<0, 0> {
- template <typename Expr>
- static inline double f(const Expr& vec) {
- return 0;
- }
- };
- template <int N, int I>
- struct dot {
- static const int loopFlag = (I < N - 1) ? 1 : 0;
- template <typename Expr1, typename Expr2>
- static inline int f(const Expr1& a, const Expr2& b) {
- return (a[I] * b[I]) + dot<loopFlag * N, loopFlag * (I + 1)>::f(a, b);
- }
- };
- template <>
- struct dot<0, 0> {
- template <typename Expr1, typename Expr2>
- static inline int f(const Expr1& a, const Expr2& b) {
- return 0;
- }
- };
- int main() {
- MyVector<int, 3> vec1;
- MyVector<int, 3> vec2;
- vec1.setElement(0, 5);
- vec1.setElement(1, 7);
- vec1.setElement(2, 8);
- vec2.setElement(0, 13);
- vec2.setElement(1, -4);
- vec2.setElement(2, 17);
- printf("%d\n", dot<3, 0>::f(vec1, vec2));
- printf("%f\n", sum<3, 0>::f(vec1));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement