使用C ++:我在这里做错了什么?

时间:2015-10-12 16:56:54

标签: c++11 type-alias

以下代码无法在最新的Microsoft Visual Studio上编译。有人可以告诉我我在这里做错了吗?

#include <iostream>
#include <iomanip>
#include <array>

template <typename T, std::size_t M, std::size_t N>
using Matrix = std::array<T, M * N>;

template <typename T, std::size_t M, std::size_t N>
std::ostream &operator<<(std::ostream &os, const Matrix<T, M, N> &matrix)
{
    for (auto i = 0; i < M; ++i)
    {
        for (auto j = 0; j < N; ++j)
        {
            os << std::setw(5) << matrix[i * N + j];
        }

        os << std::endl;
    }

    return os;
}

int main(int argc, const char * const argv[])
{
    Matrix<float, 2, 3> matrix{
        1.1f, 1.2f, 1.3f,
        2.1f, 2.2f, 2.3f
    };

    std::cout << matrix << std::endl;

    return 0;
}

以下是编译器错误的快照:

1>main.cpp(30): error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::array<T,6>' (or there is no acceptable conversion)
1>          with
1>          [
1>              T=float
1>          ]

编辑: 以下代码有效:

#include <iostream>
#include <iomanip>
#include <array>

template <typename T, std::size_t M, std::size_t N>
using Matrix = std::array<std::array<T, N>, M>;

template <typename T, std::size_t M, std::size_t N>
std::ostream &operator<<(std::ostream &os, const Matrix<T, M, N> &matrix)
{
    for (auto row : matrix)
    {
        for (auto element : row)
        {
            os << std::setw(5) << element;
        }

        os << std::endl;
    }

    return os;
}

int main(int argc, const char * const argv[])
{
    Matrix<float, 2, 3> matrix{
        1.1f, 1.2f, 1.3f,
        2.1f, 2.2f, 2.3f
    };

    std::cout << matrix << std::endl;

    return 0;
}

1 个答案:

答案 0 :(得分:2)

请记住@dyp的注释你要做的就是创建新类型而不是别名,它将有2个独立的参数。< / p>

因此,您只需将包含实际数据的聚合用作字段,例如:

template <typename T, std::size_t M, std::size_t N>
class Matrix
{
private:
    std::array<T, M * N> _data;
    template <typename T1, std::size_t M1, std::size_t N1> friend std::ostream &operator<<(std::ostream &os, const Matrix<T1, M1, N1> &matrix);
public:
    template <typename...Args>
    Matrix(Args... args):
        _data{{std::forward<Args>(args)...}}
    {}
};