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

标签 c++ c++11

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

#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/

相关文章:

c++ - Qt 中的 cin 等价物

c++ - 在类初始化和初始化列表中

c++ - 为什么 gcc 无法从其前向声明中检测到友元类命名空间?

c++ - std::initializer_list 返回成员变量返回不正确的值

c++ - 是否可以重载插入运算符 >> 以在不使用数组的情况下接收用户输入?

c++ - 运行时调用函数的类的名称

c++11 lambda高阶函数包装器递归错误

c++ - 在 C++11 使用声明中是否允许/需要 "typename"?

c++ - 当 T 具有非平凡的析构函数时,类类型 T 的对象可以进行常量初始化吗?

c++ - 除了移动语义之外,还有哪些 C++11 功能可以提高我的代码的性能?