当作为参数传入时,是否可以由编译器指定模板类参数?
Is it possible to have template class arguments specified by the compiler, when passed in as a parameter?
请考虑以下事项: 我正在用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,因为在那里它可以禁用移动语义,并且如果返回结果,乘法矩阵的语义不应该改变任何操作数。
相关文章:
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 告诉c++编译器该参数没有别名
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 推断模板参数的编译器
- 有没有办法在从编译器获取参数时避免预处理器宏?
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- 模板模板参数和模板别名:编译器错误?
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- 如何使用传递给编译器的相同参数在 cmake 中运行命令?
- 编译器是否强制根据模板参数计算表达式?
- C++自定义分配器大小参数作为模板参数会引发编译器错误
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 编译器给出错误:format 指定类型 'float *',但参数的类型'double' [-Wformat]
- 编译器确定参数是给定还是省略
- 当作为参数传入时,是否可以由编译器指定模板类参数?
- 在没有对象参数编译器错误的情况下调用非静态成员函数
- 默认模板参数编译器错误
- 缺少默认参数-编译器错误