gpt4 book ai didi

c++ - 运算符重载模板参数

转载 作者:行者123 更新时间:2023-11-28 02:19:44 24 4
gpt4 key购买 nike

所以我有一个实现矩阵的小类。一切都很好,除了让我有理由在这里发帖的原因。我已经使用注释对实际代码中的问题进行了更多解释。在此先感谢任何可以提供帮助的人!这不是整个程序,但足够大,可以自行编译。

#include <iostream>
#include <initializer_list>

template<class type_t, unsigned Rows, unsigned Columns>
class matrix
{
private:
std::initializer_list<std::initializer_list<type_t>> elements;

public:
type_t contents[Rows][Columns];

matrix() {}

matrix(const std::initializer_list<std::initializer_list<type_t>> &container)
: elements(container)
{
unsigned i = 0;
for (const auto &el : elements)
{
unsigned j = 0;
for (const auto &num : el)
{
contents[i][j] = num;
j++;
}
i++;
}
}

unsigned rows() { return Rows; }
unsigned columns() { return Columns; }

type_t &operator()(const unsigned &i, const unsigned &j)
{
return contents[i][j];
}

template<unsigned rws, unsigned cls>
auto operator*(matrix<type_t, rws, cls> &mat)
{
matrix<type_t, Rows, 3> ret_mat; //OK, but only in case the return matrix has 3 columns
matrix<type_t, Rows, mat.columns()> ret_mat; //Error. This is the desired result
//The error message tells me it needs to be a compile-time constant
//it's pretty obvious why the first works and what the problem is
//but i still have no idea how to get past this

for (unsigned i = 0; i < this->rows(); ++i)
{
for (unsigned j = 0; j < mat.columns(); ++j)
{
for (unsigned in = 0; in < 2; ++in)
ret_mat.contents[i][j] += this->contents[i][in] * mat.contents[in][j];
}
}

return ret_mat;
}
};

int main()
{
matrix<int, 4, 2> mat = { { 7, 3 },{ 2, 5 },{ 6, 8 },{ 9, 0 } };
matrix<int, 2, 3> mat2 = { { 7, 4, 9 },{ 8, 1, 5 } };

auto mat3 = mat * mat2;

for (unsigned i = 0; i < mat3.rows(); ++i)
{
for (unsigned j = 0; j < mat3.columns(); ++j)
std::cout << mat3(i, j) << " ";
std::cout << std::endl;
}
std::cin.get();
}

最佳答案

template<unsigned rws, unsigned cls>

你已经有了想要的表情!

matrix<type_t, Rows, cls> ret;

编辑:如@juanchopanza 所述,为什么允许 N*M 在 K*L 上与 M != K 相乘?应该是

template<unsigned cls>

auto operator*(matrix<type_t, columns, cls> &mat)
{
matrix<type_t, Rows, cls> ret_mat;

关于c++ - 运算符重载模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32931661/

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