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

C++ introduce 'new' template arguments

本文关键字:参数 new C++ 引入      更新时间:2023-10-16

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

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);
}