C ++ operator overload, (+, -, *, / etc.) Is there a smarter way than copying, replacing and pasting?

I am writing some kind of matrix library, so I gave my matrix 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 works. Now I like to add operators -, /, *, they all work the same way. Of course, I can use copy, replace and paste. But this is bad for readability and maintainability. Is there a more reasonable solution and possibly a concept, since I don’t know the name of the concept for google? I just found how to overload one statement.

+4
source share
2 answers

template rvalue reference && ( -, ):

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;
}

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);
}
+11

, + - on , * / - + - - .

, , , ( 7- 7- ).

, , ... .

0

Source: https://habr.com/ru/post/1684356/


All Articles