J
Jojo
Is there any way to get to the left-hand side of an operator? Consider
the following (this is not meant to be perfect code, just an example of
the problem):
class Matrix
{
public:
int data[1024];
Matrix() {}
Matrix(int value)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
data = value;
}
void add(const Matrix& obj, Matrix* output)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
output->data = data + obj.data;
}
Matrix operator +(const Matrix& obj)
{
Matrix temp; // "unnecessary" creation of temp variable
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
temp.data = data + obj.data;
return temp; // "unnecessary" extra copy of output
}
};
For nice looking syntax you _really_ want to use the operator+ like:
matrix3 = matrix1 + matrix2;
However, that is some 50% slower than the _much_ uglier:
matrix1.add(matrix2, &matrix3);
If only there were a way to get to the left-hand argument of the
operator+ then it could be fast and easy to use. Consider the following
code which is not valid C++ and will not compile for this example:
Matrix as M
operator+(const Matrix& obj)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
M.data = data + obj.data;
}
That would be fast and clean to use. Is there any way to accomplish
this? Otherwise the situation is just ugly and there is no point in
using operator overloading for these types of situations (which really
defeats the purpose of operator overloading in the first place).
Thanks! Jo
the following (this is not meant to be perfect code, just an example of
the problem):
class Matrix
{
public:
int data[1024];
Matrix() {}
Matrix(int value)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
data = value;
}
void add(const Matrix& obj, Matrix* output)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
output->data = data + obj.data;
}
Matrix operator +(const Matrix& obj)
{
Matrix temp; // "unnecessary" creation of temp variable
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
temp.data = data + obj.data;
return temp; // "unnecessary" extra copy of output
}
};
For nice looking syntax you _really_ want to use the operator+ like:
matrix3 = matrix1 + matrix2;
However, that is some 50% slower than the _much_ uglier:
matrix1.add(matrix2, &matrix3);
If only there were a way to get to the left-hand argument of the
operator+ then it could be fast and easy to use. Consider the following
code which is not valid C++ and will not compile for this example:
Matrix as M
operator+(const Matrix& obj)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
M.data = data + obj.data;
}
That would be fast and clean to use. Is there any way to accomplish
this? Otherwise the situation is just ugly and there is no point in
using operator overloading for these types of situations (which really
defeats the purpose of operator overloading in the first place).
Thanks! Jo