为什么在C++中允许重新声明模板成员函数?

class test{
 public:
 int call();
};

int test::call();

int main(){return 0;}

上面的不会编译,出现这个错误:

error: declaration of 'int test::call()' outside of class is not definition 

但是,如果这样使用模板,则允许使用相同的代码:

class test{
 public:
 template<class T>
 int call();
};

template int test::call<int>(); // what's the point of this line?

template <class T>
int test::call(){
  T in = 5;
  return in;
}

int main(){
 test t;
 
 return 0;
}

我有两个问题:

1-重新声明有什么意义?我在其他项目中看到过类似的代码。

2- 为什么它可以编译而我的第一个代码片段却不能?

回答

这不是声明,而是定义。这称为函数模板的显式模板实例化。

这会强制编译器int在您的情况下实例化版本。您还可以为多种类型添加显式实例化:

class test{
 public:
 template<class T>
 int call() { return 0; }
};

template int test::call<int>();
template int test::call<float>();

通过控制实例化发生的时间来加快编译速度或控制实例化要求的可见性非常有用。这通常与以下extern template功能相结合:

// ------------------
// ----- test.h -----
// ------------------
class test{
 public:
 template<class T>
 int call();
};

// Here, we tell the compiler that the instantiation exists somewhere
// That somewhere may not visible, so the compiler won't try to instantiate it
extern template int test::call<int>();
extern template int test::call<float>();


// ------------------
// ---- test.cpp ----
// ------------------

#include "test.h"

// define the template in the cpp only
template <class T>
int test::call(){
  T in = 5;
  return in;
}

// provide definitions for the instantiations:
template int test::call<int>();
template int test::call<float>();


以上是为什么在C++中允许重新声明模板成员函数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>