定义模板类,但获取'is not a class template'

Define a template class but get 'is not a class template'

本文关键字:not is class template 获取 定义      更新时间:2023-10-16

我们试图使用模板定义类:

template<typename _VType, size_t _Len>
class Obc<_VType,_Len> {
  private:
    size_t len = _len;
  public:
    Obc();
    Obc(_VType *values);
    ...
};

,我们希望能够像:

一样使用它
Obc<_DType, 2> m = new Obc();

但是,"'矩阵"不是类模板"。

我们尝试通过搜索"不是类模板"而找到的SOL,例如" X不是模板"错误,但还没有运气

有什么想法?

不要重复您的模板参数:

template<typename _VType, size_t _Len>
class Obc {
  ...
};

并假设_DType是现有类型,请使用模板类参数,而不使用Java语法,例如:

Obc<_DType, 2> m;
Obc<_DType, 2> mat{values};    // assuming _DType *values point to something
auto othermat = mat; 

在线演示

我们试图使用模板定义类:

template<typename _VType, size_t _Len>
class Obc<_VType,_Len> {
  private:
    size_t len = _Len;
  public:
    Obc();
    Obc(_VType *values);
    ...
};
and, we expected to be able to use it like:

使用中的编译器认为OBC是一种专业化,这不是一个专业化,因此错误是'x不是模板':

下面的示例更清楚地解释了(请参阅评论):

template <typename VType, size_t Len> 
class Obc { //Non-specialized
  private:
    size_t len = Len;
  public:
    Obc(){}
    Obc(VType *values){}
};
template<typename VType>
class Obc<VType,5> { //Partially specialized for size_t = 5
  //... expects non-specialized declaration
  private:
    size_t len = 5;
  public:
    Obc(){}
    Obc(VType *values){}
};
class X{};
int main() {
  // Using new like this... bad style... leak...
  auto m = new Obc<X, 5>(); //Instantiates specialization
  auto n = new Obc<X, sizeof(X)>(); //Instantiates original
  // your code goes here
  return 0;
}

btw,使用新来创建OBC意味着它是在堆上创建的,这是(1)并非总是必要的,并且(2)在完成后,应取消分配。在这种情况下,应与某种Smart_ptr包裹,例如unique_ptr或shared_ptr,具体取决于所有权语义:

宁愿做(在上面的示例中):

...
  Obc<X, 5> m{}; //Instantiates specialization
//or
  auto ptr = std::make_shared<Obc<X,5>>(); 
  //...Or some other smart pointer type
...