I am writing a kind of matrix-library, so I gave my matrix a operator +
, using operator overloading. It looks something like this.
friend matrix<T, size_x, size_y> operator + (const matrix<T, size_x, size_y> & Input_1, const matrix<T, size_x, size_y> & Input_2){
matrix<T, size_x, size_y> Output;
for (int i=0; i<size_x; i++){
for (int j=0; j<size_y; j++){
Output.value[i][j]=Input_1.value[i][j]+Input_2.value[i][j];
}
}
return Output;
}
As far, as I tested it, it works. Now I like to add the -, /, * operators too, they all work the same. Of course I can use copy, replace and paste. But this is bad for readability and maintainability. Is there a smarter solution and perhaps a concept, since I don't know the name of the concept to google it? I just found, how to overload a single operator.
You might use a template and a rvalue reference &&
(needed for a temporary lambda expression that is created when calling):
template <typename F>
friend matrix<T, size_x, size_y> doBinOp(F&& f,
const matrix<T, size_x, size_y> & Input_1,
const matrix<T, size_x, size_y> & Input_2)
{
matrix<T, size_x, size_y> Output;
for (int i=0; i<size_x; i++) {
for (int j=0; j<size_y; j++) {
Output.value[i][j] = f(Input_1.value[i][j], Input_2.value[i][j]);
}
}
return Output;
}
And then
friend matrix<T, size_x, size_y> operator + (const matrix<T, size_x, size_y> & Input_1,
const matrix<T, size_x, size_y> & Input_2)
{
return doBinOp([](auto l, auto r) { return l + r; }, Input_1, Input_2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With