Sunday, October 16, 2016

Delayed Evaluation and Expression template

Instead of loop through vector index multiple times when adding mutiple vector.
could keep ref to sum of two and later loop-through once to reduce temp var

#include <iostream>
#include <vector>
#include <cstdlib>

using namespace std;

// temp var one-by-one
//template<typename T>
//inline vector<T> operator+(const vector<T>& x, const vector<T> y)
//{
// vector<T> sum(x.size());
// for(int i=0;i<x.size();i++)
//  sum[i]=x[i]+y[i];  //temp var
// return sum;
//}

// delayed evaluation expression template

template <typename T>
struct vector_sum
{
 const vector<T> &x, &y;
 vector_sum(const vector<T> &x, const vector<T> &y) :x(x), y(y) {}
 T operator[](int i) const { return x[i] + y[i]; }  // indexer
};

template<typename T>
vector_sum<T> operator+(const vector<T>& x, const vector<T>& y)
{
 return{ x,y }; // delayed evaluation to a single loop
};

template<typename T> class vector  // new impl of vector
{
 const vector<T> &data;
 vector& operator=(const vector_sum<T>& that)  //assignment
 {
  check_size(size(that));
  int my_size = size(that);
  for (int i = 0; i<my_size; ++i)
   data[i] = that[i];  // now loop through.
  return *this;
 }
};

int main() {
 std::vector<int> x = { 1,2,3 };
 std::vector<int> y = { 4,5,6 };
 auto s = x + y;
 cout << s[2] << endl;

 return 0;
}

No comments:

Post a Comment