gpt4 book ai didi

C++ 引入 'new' 模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 01:35:55 26 4
gpt4 key购买 nike

我正在尝试使用模板参数中给定的维度和类型创建一个可重用的矩阵类。结构本身就是:

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)

顺便说一句,我正在使用 MSVC 和 Visual Studio。

最佳答案

so calling would become 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;

关于C++ 引入 'new' 模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513973/

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