gpt4 book ai didi

c++ - 模板类成员函数的参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:41:52 26 4
gpt4 key购买 nike

我正在努力更好地理解模板,并转向了优秀的“ole 矩阵类”。我知道 eigen、armadillo 等。我的目的是更好地理解模板。我的问题是如何让成员函数接受一个参数,该参数是同一模板类的对象,但具有不同的特化?

例如,我试图组合在一起的矩阵类采用两个模板参数——行数和列数。此外,任何 m x n 矩阵对象 ( Matrix<mRows,nCols> ) 应该能够采用 n x p 矩阵对象 ( Matrix<nCols,pCols> ) 并将它们相乘并返回 m x p 矩阵对象 ( Matrix<mRows,pCols> ):

template <unsigned mRows, unsigned nCols>
class Matrix
{
private:
double matrixData[mRows][nCols];
//...other stuff
public:
//...other stuff

Matrix operator * (const Matrix<nCols, pCols>& rhs);
}

// simple naive matrix multiplication method
template <unsigned mRows, unsigned nCols>
Matrix<nCols,pCols> Matrix<mRows, nCols>::operator * (const Matrix<nCols,pCols>& rhs)
{
Matrix<nCols,pCols> temp();

for (int r = 0; r<mRows; ++r)
{
for(int c = 0;c<pCols;++c)
{
temp.matrixData[r][c]=0;
for (int elem = 0; elem<nCols;++elem)
{
temp.matrixData[r][c]+= matrixData[r][elem]*rhs.matrixData[elem][c];
}
}
}

return temp;
}

主要功能是这样的:

int main() 
{
Matrix<2,3> m1;
Matrix<3,4> m2;

//...initialize matrices...

Matrix<2,4> m3 = m1 * m2;

}

这不起作用,因为没有在任何地方声明 pCols。在哪里/如何申报?

最佳答案

在您的情况下,您必须使用函数模板定义中可用的模板参数来专门化 Matrix 类:

template <unsigned mRows, unsigned nCols>
Matrix<mRows,nCols> Matrix<mRows, nCols>::operator * (const Matrix<nCols,mRows>& rhs)

然后,您最好在声明和定义中对模板参数使用一致的命名约定。

将模板参数视为可供您在其后的实体中使用的类型/常量。声明是定义,在此上下文中本质上是独立的实体(这就是为什么在提供函数定义时需要第二次键入 template<> 的原因)。

编辑:再仔细看了一遍问题,原来我的回答没有说​​到点子上。 Columbo 的回答是要走的路。

关于c++ - 模板类成员函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27154754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com