从C ++中将非常量整数传递给模板参数 [英] Pass non constant integer to template arguments from in C++

查看:78
本文介绍了从C ++中将非常量整数传递给模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何创建一个大小从命令行给出的矩阵.如果它是非模板矩阵类,则可以轻松完成.但是,如果矩阵类是模板类(例如在Eigen中),该如何创建一个大小从命令行给出的矩阵呢?

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

感谢@hyde和@marcinj.我以为Eigen的实现背后有某种神奇的机制.通过再次查看Eigen的代码,我认为他们仅对小型矩阵使用模板参数int _Cols, int _Rows,并将Dynamic定义为类似于-1的一些常量,并在运行时进行处理.

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.

推荐答案

答案是你不能,模板在编译时实例化,因此row和col也必须在编译时知道.

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

您将必须实现一个非模板化的Matrix类,以实现所需的功能.将行/列传递给构造函数,并允许类为矩阵动态分配内存.

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.

如果您想以与Eigen中类似的方式实现Matrix,则也将研究它们的实现.在这里:

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

您可以看到他们的模板化Matrix接受row和col作为模板参数,当参数具有某些指定值Dynamic(这可能是一些非常大的值,例如std::numeric_limits<unsigned int>::max())时,则Matrix使用如下所示的矩阵大小构造函数参数.

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.

这篇关于从C ++中将非常量整数传递给模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆