Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator-overloading C++, (+, -, *, / etc.) Is there a smarter way than copy, replace and paste?

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.

like image 598
Markus Avatar asked Dec 19 '22 04:12

Markus


1 Answers

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);
}
like image 63
Jarod42 Avatar answered Dec 24 '22 00:12

Jarod42