当作为参数传入时,是否可以由编译器指定模板类参数?

Is it possible to have template class arguments specified by the compiler, when passed in as a parameter?

本文关键字:参数 编译器 是否      更新时间:2023-10-16

请考虑以下事项: 我正在用C++编写一个矩阵类,它看起来像这样:

template<unsigned rows, unsigned cols>
class matrix
{
...
};

现在,编写乘法方法,我遇到了一个问题:左边的 - "这个" - 矩阵必须具有与右边 - "o" - 矩阵有行相同的列数,但 o 有多少列无关紧要,见下文:

const matrix<rows, rows> mul(const matrix<cols, /*This can be anything*/>&& o)
{
...
}

我的问题是,有没有办法告诉编译器,它应该采用 o 的模板参数作为其未知的第二个参数?

有什么方法可以告诉编译器,它应该采取 O 的模板参数为其未知的第二个参数?

是的,这正是模板为您所做的:( 只需将mul()编写为成员函数模板而不是成员函数即可。

template<unsigned rows, unsigned cols>
class matrix
{
...
template <unsigned rhsRows>
matrix<rows, rhsRows> mul(const matrix<cols, rhsRows>& o) const
{
...
}
};

注意:const被移动到使成员函数模板const而不是返回值的const,因为在那里它可以禁用移动语义,并且如果返回结果,乘法矩阵的语义不应该改变任何操作数。