Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c++ - how to make template function (operator) deduce template arguments implicitly?

I have this code which I need to make it be compiled:

int main () {
    const Matrix<int, 3, 2> m1; // Creates 3*2 matrix, with all elements set to 0;
    Matrix<int, 3, 3> m2(4); // Creates 3*3 matrix, with all elements equals to 4;
    const Matrix<int, 3, 3> m3 = m2; // Copy constructor may take O(MN) and not O(1).
    cout << m3 * m1 << endl; // You can choose the format of matrix printing;

I already implemented the operator<< for the template matrix. the problem is to create operator* such that create a new matrix with the template params of m3.rows and m1.cols, the problem it's to define the return type in the signature of operator*.

I tried:

Matrix<int, lhs.rows, rhs.cols> operator *(const MatrixBase& lhs, const MatrixBase& rhs)
Matrix<?> res; // not sure how to define it
{
    for (int i = 0; i < lhs.get_columns(); i++)
    {
        for (int j = 0; j < rhs.get_rows(); j++)
        {
            for (int k = 0; k < lhs.get_columns(); k++)
            {
                res[i][j] = lhs[i][k] * rhs [k][j];
            }
        }
    }
}

the class MatrixBase is just a non-template abstract class that Matrix are derivedfrom, a try to make operator* generic. the problem is that lhs and rhs are not initialized yet and it does not compile, I thought of making the operator* as a method of Matrix but I still stuck on the return type. I know that template determined with the preprocessor but I'm sure that there is a way to make it run.

question from:https://stackoverflow.com/questions/65860052/how-to-make-template-function-operator-deduce-template-arguments-implicitly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your questions lacks some information about what MatrixBase is, but if we just look at your Matrix class you need a template function to do this. There you can deduce the template parameters of the classes and use that to calculate the resulting type.

template <typename T, int LRows, int LCols, int RRows, int RCols>
Matrix<T, LRows, RCols> operator*(const Matrix<T, LRows, LCols>& lhs, const Matrix<T, RRows, RCols>& rhs) {
    static_assert(LCols == RRows, "Invalid matrix multiplication");
    Matrix<T, LRows, RCols> result;
    // ... do the calculations
    return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...