C++ 史上最华而不实的类

来源:互联网 发布:ug8.0编程中的建模创 编辑:程序博客网 时间:2024/06/01 08:21

下面大家要看到这个类完全是扯淡,一无是处。它是由感而发于帖子C++的二维数组转置。

当时,看完帖子我就在想,能不能用重载的方式实现逻辑转置?只是好奇。C++显然是不能重载两个 [][] ,但是要达到这个效果,只要让 [] 操作符返回一个指针即可。

问题是这样根本做不到一个逻辑上的转置,经与码友讨论生出用两个类重载[]操作符这么一条计策。于是,便产生了它。

它“华”到一个模板类中还定义有一个嵌套类,“不实”到没有任何人会在工程当中用它。

点此查看运行效果

#include <iostream>template<typename T, size_t columns>class TransMatrix {  using Matrix = T(*)[columns];  class Column {   public:    const T& operator[](const size_t column_index) const {      return m_[column_index][line_index_];    }      private:    friend class TransMatrix;    Column(const Matrix P, size_t lines) : m_(P), lines_(lines) { }     const Matrix m_;     const size_t lines_;    size_t line_index_;  };   public:  TransMatrix(Matrix m, size_t lines) : column_(Column(m, lines)) { }   Column& operator[](const size_t line_index) {    column_.line_index_ = line_index;    return column_;  } private:  Column column_;};int main(int argc, char* argv[]) {  constexpr int kColumns = 4;  int a[3][kColumns] = {     { 1, 2, 3, 4 },    { 5, 6, 7, 8 },    { 9, 10, 11, 12 }  };    TransMatrix<int, kColumns> trans(a, 3);   for (int i = 0; i < 4; i++) {    for(int j = 0; j < 3; j++) {      std::cout << trans[i][j] << ", ";    }       std::cout << std::endl;  }  std::cout << std::endl;}
原创粉丝点击