简体   繁体   English

在类之外定义“模板化类”函数

[英]Defining “templated class” functions outside of a class

I have this class 我有这门课

template <class T> class dynamic_array
  {

and this function: 而这个功能:

void dynamic_array::randorder()
  {
  srand(time(NULL));
  int *ap;
  for(ap=array;k!=array+size;++k){*k=rand();} 
  }

The compiler is complaining about my function - "not having template parameters". 编译器抱怨我的功能 - “没有模板参数”。 How do I add this in? 我该如何添加?

template <class T>
void dynamic_array<T>::randorder()
{
  srand(time(NULL));
  for(int *ap = array; k != array + size; ++k)
  {
    *k = rand();
  }
}

It should be 它应该是

template <class T>
void dynamic_array<T>::randorder()
  {
...
  }

Also, keep in mind that you have to put the definition into a header file if you need to use it in different .cpp files. 另外,请记住,如果需要在不同的.cpp文件中使用它,则必须将定义放入头文件中。

I suppose array must be a data member of type T , so the following doesn't apply here. 我想array必须是T类型的数据成员,因此以下内容不适用。 But in general if you see that some member functions of a class template do not depend on the template parameters, it makes sense to factor them out into a non-template base class. 但总的来说,如果您发现类模板的某些成员函数不依赖于模板参数,那么将它们分解为非模板基类是有意义的。 It reduces the size of the executable and makes your life easier. 它减少了可执行文件的大小,让您的生活更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM