C++引入'new'模板参数
C++ introduce 'new' template arguments
我正在尝试使用模板参数中给定的维度和类型创建一个可重用的矩阵类。结构本身只是:
template <unsigned int N, unsigned int M, typename T>
struct Matrix
{
T elements[N* M];
};
当我尝试实现矩阵乘法时,我遇到了一个问题,需要引入新的模板参数。原始矩阵的大小是N*M。第二个矩阵的大小为L*N,结果矩阵为N*K。所以乘法函数看起来像:
Matrix<N, K, T> Multiply(const Matrix<L, N, T>& other) {... }
但是我需要为函数创建一个模板,所以调用将变成mat.Multiply<x, y>(mat2)
,这意味着我必须指定两次内容。有办法避免这种情况吗?(类似Matrix<N, unsigned int K, T>
)
编辑:我试过这个:
template <unsigned int K, unsigned int L>
Matrix<N, K, T> Multiply(const Matrix<L, N, T>& other)
在这段代码中,我得到了一个错误,说没有函数模板的实例与参数列表匹配:
Matrix<3, 2, int> mat;
Matrix<2, 3, int> mat2;
mat.Multiply(mat2)
顺便说一句,我正在使用微软风投和Visual Studio。
所以呼叫将变成
mat.Multiply<x, y>(mat2)
如果乘法成员函数是一个类似的函数模板
template <unsigned int N, unsigned int M, typename T>
struct Matrix
{
template <unsigned int L>
Matrix<N, L, T> Multiply(const Matrix<M, L, T>& other) {... }
T elements[N * M];
};
然后模板参数推导允许您调用这样的函数:
mat.Multiply(mat2)
注意:您可能也应该考虑实现一个非成员operator*
,以实现以下功能:
auto mat3 = mat * mat2;
Multiply
也是模板是正常的。注意,K == L
用于乘法。
template <unsigned int N, unsigned int M, typename T>
struct Matrix
{
template <unsigned int K>
Matrix<N, K, T> Multiply(const Matrix<M, K, T>& other) const {/*..*/}
T elements[N* M];
};
在调用中,所有模板参数都是可推导的,因此您可以这样调用它:
int main()
{
const int N = 4;
const int M = 5;
const int K = 6;
using T = float;
Matrix<N, M, T> rhs;
Matrix<M, K, T> lhs;
Matrix<N, K, T> res = rhs.Multiply(lhs);
}
相关文章:
- 运算符 new 的执行顺序和构造函数的参数
- 在执行new期间是否可以在构造函数中传递不同的参数?
- 重载运算符 new 和运算符 delete 带有三个参数
- 构造函数不会将使用 new 初始化的数组作为参数
- 默认参数中的 c++ new 运算符及其副作用
- 如何传递 ObjectTemplate::New in Google V8 的第二个参数
- 使用new运算符可以将参数作为函数中数组的大小来分配整数数组
- 作为参数的"new Foo()"和"&Foo()"之间的区别
- 有没有办法根据参数使用'new XXXX'?
- 使用可选参数重载 new 和 delete 运算符
- 在不使用"new"的情况下实例化参数参数中的对象
- C++引入'new'模板参数
- 'operator new':函数不接受 2 个参数
- 错误 C2661:'CObject::operator new':没有重载函数需要 4 个参数
- 通过数组和"new"运算符创建的对象,但如何传递参数?
- 错误 35 错误 C2661:'operator new':没有重载函数占用 2 个参数
- 在没有提供参数的情况下,如何调用我的重载new
- 如何使用"new"在函数内分配点引用参数的内存
- 在覆盖new操作符时传递更多参数(c++)
- c++的NEW对象作为参数(和Java一样)