Skip to content

Instantly share code, notes, and snippets.

@KoKuToru
Created January 2, 2015 13:33
Show Gist options
  • Select an option

  • Save KoKuToru/1d23af4bbf0b2bc89893 to your computer and use it in GitHub Desktop.

Select an option

Save KoKuToru/1d23af4bbf0b2bc89893 to your computer and use it in GitHub Desktop.
Efficient Sum and Assignment operator overloading in C++
/**
* Delayed add,sub,mul,div of a Matrix
* mul,div is by element. Not a real Matrix mul,div !
*
* Just shows the idea of delaying calculations..
*/
//Should never be used outside, is a helper class
class MatAccess {
public:
virtual double operator[](int index) const = 0;
};
//Should never be used outside, stores the operation
template<int op>
class MatOp: public MatAccess {
public:
const MatAccess& left;
const MatAccess& right;
MatOp(const MatAccess& left, const MatAccess& right):
left(left), right(right) {
//todo check if left/right is same size
}
double operator[](int index) const {
switch(op) {
case '+':
return left[index] + right[index];
case '-':
return left[index] - right[index];
case '*':
return left[index] * right[index];
case '/':
return left[index] / right[index];
default:
return 0;
}
}
};
//holds the matrix data
class Mat: public MatAccess{
public:
double* data;
int rows,cols;
Mat(int r,int c):rows(r),cols(c) {
data = new double[r*c];
}
Mat() = delete;
Mat(const Mat& o) = delete;
~Mat() {
delete[] data;
}
const Mat& operator = (const MatAccess& other) {
//todo check if other is same size
for(int i = 0; i < rows*cols; ++i) {
data[i] = other[i];
}
return *this;
}
double operator[](int index) const {
return data[index];
}
double& operator[](int index) {
return data[index];
}
};
//operator overloads
const MatOp<'+'> operator+(const MatAccess& left, const MatAccess& right) {
return MatOp<'+'>(left, right);
}
const MatOp<'-'> operator-(const MatAccess& left, const MatAccess& right) {
return MatOp<'-'>(left, right);
}
const MatOp<'*'> operator*(const MatAccess& left, const MatAccess& right) {
return MatOp<'*'>(left, right);
}
const MatOp<'/'> operator/(const MatAccess& left, const MatAccess& right) {
return MatOp<'/'>(left, right);
}
//Little example
#include <assert.h>
int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);
Mat D(300,300);
Mat E(300,300);
A[0] = 1;
B[0] = 2;
C[0] = 3;
D[0] = 2;
E = (A + B) / C + D;
assert(E[0] == (A[0] + B[0]) / C[0] + D[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment