Search code examples
c++templatesmatrixnon-type-template-parameter

How can I pass a non-constant int as a template argument?


I wonder how can I create a matrix whose size is given from command line. It can be done trivially if it is a non template matrix class. But what if the matrix class is a template class (like in Eigen), how can I do to create a matrix whose size is given from command line?

template<int _row, int _col>
class Matrix{
...
};

int main{
    // assign rows and cols dynamically
    int row;
    int col;
    std::cin >> row >> col;

    // Some procedures

    Matrix<row, col> m;
    return 0;
}

Edit:

Thanks @hyde and @marcinj. I thought there are some magic mechanism behind Eigen's implementation. By looking into the Eigen's code again, I think they use template arguments int _Cols, int _Rows only for small matrix and define Dynamic to be some constants like -1 and handle it on runtime.


Solution

  • The answer is you cannot, templates are instantiated at compile time so row and col would have to be known at compile time too.

    You will have to implement a non templated Matrix class to achive what you want. Pass row/col to constructor and allow class to dynamically allocate memory for the matrix.

    [edit]

    If you want to implement your Matrix in similar way as in Eigen, you will have too look into their implementation. In here:

    https://eigen.tuxfamily.org/dox/classEigen_1_1Matrix.html

    you can see that their templated Matrix accepts row and col as template parameter, when parameter is of some specified value Dynamic (this might be some very large value like std::numeric_limits<unsigned int>::max()), then Matrix uses matrix sizes as provided in constructor parameters.

    If code for dynamic template matrix should be significantly different then you could provide specialization for it.