matrix - C++: Overloading multiple operators in a single function? -


good afternoon! still new coding business, please bare me. wanted know if there's way overload many operators using single function?

i'm making simple program manipulate matrices using +,-,*,/ operators, instead of copy , pasting code each new one, there way have 1 overload function work kind of switch?

matrix matrix::operator+(int scalar) {     matrix newest(row, col);      (int = 0; < row; ++i) {         (int j = 0; j < col; ++j) {             newest.matrix[i][j] = matrix[i][j] + scalar;         }     }     return newest; }  matrix matrix::operator-(int scalar) {     matrix newest(row, col);      (int = 0; < row; ++i) {         (int j = 0; j < col; ++j) {             newest.matrix[i][j] = matrix[i][j] - scalar;         }     }     return newest; }  matrix matrix::operator*(int scalar) {     matrix newest(row, col);      (int = 0; < row; ++i) {         (int j = 0; j < col; ++j) {             newest.matrix[i][j] = matrix[i][j] * scalar;         }     }     return newest; } matrix matrix::operator/(int scalar) {     matrix newest(row, col);      (int = 0; < row; ++i) {         (int j = 0; j < col; ++j) {         newest.matrix[i][j] = matrix[i][j] / scalar;         }     }     return newest; } 

is there way condense instead of having make 4 separate functions, can make 1 overloading function , have determine operator called , work that?

you can't "generify" operator symbol , implement "operator any_op" function.

you can make 1 generic function , forward that, though.
this:

matrix matrix::operate(std::function<int(int,int)> fn, int scalar) {     matrix newest(row, col);         (int = 0; < row; ++i) {         (int j = 0; j < col; ++j) {             newest.matrix[i][j] = fn(matrix[i][j], scalar);         }     }     return newest; }  matrix matrix::operator-(int scalar) {     return operate(std::minus<int>(), scalar); }  matrix matrix::operator+(int scalar) {     return operate(std::plus<int>(), scalar); }  // , other operators. 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -