Template Specialization指针指针和数组传递模板推导

时间:2013-09-12 04:49:01

标签: c++ arrays templates

我正在编写以下代码来测试模板专业化。有没有办法让指针衰减到类型,以便我可以使用模板参数推导来获得我的M和N所以我可以有二维数组的行和列?我知道我可以为2d数组的向量矢量,但这是模板专业化的练习。下面的代码按原样工作,但是看看你是否取消注释以下内容并注释掉当前的T **构造函数它不起作用。因此,构造函数当前硬编码用于删除data_成员的行数,这不理想,理想情况下我会从模板推导中获取此参数。我想知道是否有办法在下面的代码中使用它。

        //doesn't like this constructor
    //  template <unsigned int M, unsigned int N>
    //  Data ( T (&d)[M][N]  ): data_(d), rows_(M), cols_(N) {};

#include <iostream>

template <typename T>
class Data
{
  public:
  Data ( const T& d ): data_(d) {};
  Data ( T&& d ): data_(std::move(d)) {};

  std::string getType() { return "Plain Data Type"; }

  private: 
  T  data_;
};


template <typename T>
class Data<T**>
{
  public:

    //doesn't like this constructor
//  template <unsigned int M, unsigned int N>
//  Data ( T (&d)[M][N]  ): data_(d), rows_(M), cols_(N) {};
  Data ( T** d ): data_(d), rows_(25) {};
  ~Data() { 

    for ( unsigned int i = 0; i < rows_; ++i)    
    {
      delete [] data_[i];
    }
    delete [] data_;
  }

  std::string getType() { return "Pointer to Pointer Data Type"; }

  private:
  T**  data_;
  unsigned int rows_;
  unsigned int cols_;
};


template <typename T>
class Data<T*>
{
  public:
  Data ( T* d ): data_(d) {};
  ~Data() { delete data_; }

  std::string getType() { return "Pointer Data Type"; }

  private:
  T*  data_;
};


int main ( int argc, char *argv[])
{
  float f(9.65);
  Data<int> d1(f);
  std::cout << d1.getType() << std::endl;

  int *i = new int(5);
  Data<int*> d2(i);
  std::cout << d2.getType() << std::endl;

  int **j = new int*[25];
  for ( int i = 0 ; i < 25; ++i)
    j[i] = new int[50];

  Data<int**> d3(j);
  std::cout << d3.getType() << std::endl;
}


output:
Plain Data Type
Pointer Data Type
Pointer to Pointer Data Type

1 个答案:

答案 0 :(得分:2)

T**T[n][m]不等同(我诅咒那些拒绝教导这种情况的大学教授)。一个是指向指针的指针,另一个是大小为T[m]的{​​{1}}数组。

您可以像这样专门化您的2D数组类型:

n

使用它的一种方法是:

template<typename T, size_t N, size_t M>
class Data<T[N][M]>
{
public:
    Data(const T(&ar)[N][M])
    {
        for (size_t i=0;i<N;++i)
            std::copy(std::begin(ar[i]), std::end(ar[i]), std::begin(data[i]));
    }

    std::string getType() { return "2D-Fixed Array Data Type"; }

private:
    T data[N][M];
};

<强>输出

2D固定阵列数据类型