mess with templates
Jun 20, 2012 at 7:47pm UTC
In the following NON-working code, I want to minimize the double of code.
operator+ has exactly the same code for both Matrix, Vector.
Is there a way to keep it one and not duplicate it in both Matrix, Vector?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
template <class T>
struct T
{
T operator +(const T &t)
{
assert(t.size() == size());
T r(size());
for (size_t z = 0; z < size(); z++)
r[z] = (*this )[z] + t[z];
return r;
}
};
struct Matrix : public std::vector<double >, public T<Matrix>
{
Matrix(size_t sz) : std::vector<double >(sz) {}
// distinct functionality in Matrix
};
struct Vector : public T<Vector>
{
Vector(size_t sz) : p(new double [sz]), sz(sz) {}
size_t size() { return sz; }
double &operator [](size_t n) { return p[n]; }
const double operator [](size_t n) { return p[n]; }
// distinct functionality in Vector
protected :
double *p;
size_t sz;
};
Of course code like following creates the ultimate pollution...
1 2
template <class T>
T operator +(const T &t1, const T &t2);
There are many identical code parts that I want to eliminate.
This code simplified for the posting needs.
Last edited on Jun 20, 2012 at 7:49pm UTC
Topic archived. No new replies allowed.