运算符重载模板参数

运算符重载模板参数

因此,我有一个实现矩阵的小类。一切正常,除非有任何原因使我有理由在此处发布。我已经使用注释在实际代码中详细说明了该问题。在此先感谢任何可以提供帮助的人!这不是整个程序,但足够大,因此可以自行编译。

#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所提到的,为什么要允许K * L上的N * M与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/

10-11 14:37