2015-10-12 47 views
0

以下代码不能在最新的Microsoft Visual Studio上编译。有人能告诉我我在做什么错吗?使用C++使用:我在这里做错了什么?

#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; 
} 
+4

随着'N * M'通过'的std :: array'间接:

所以,你只需要使用聚合包括实际数据作为一个字段,如),独立推导'N'和'M'是不可能的。请注意,类型别名的实例化与它们引用的类型相同,也就是说,第二个'operator <<'参数等同于'const std :: array &matrix' – dyp

+1

@dyp,可能您应该让它成为答案 – Lol4t0

+0

谢谢,我现在明白了! – 0ca6ra

回答

2

记@ DYP的评论轴承你必须做什么这里是创建的新类型而不是别名那将有2个独立的pa公羊。在`运营商<<'(的模板参数

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)...}} 
    {} 
}; 
相关问题