对完整模板专业类成员功能的未定义引用,但不是部分专业化

undefined reference to full template specialization class member function, but not partial specialization

本文关键字:引用 未定义 专业化 功能 成员      更新时间:2023-10-16

因此,当使用模板实例化使用完整的模板类专业化时,我遇到了一个未定义的参考错误,但是问题是,部分模板类专业化毫无疑问。

代码如下所示,有人知道为什么吗?在这种情况下,完整的专业化和部分专业化有什么区别?

预先感谢。

// t.h
#include <iostream>
using namespace std;
template <typename T1, typename T2> 
class A { 
  public:
  void foo();
};
// t2.cpp
#include "t.h"
template<typename T1> 
class A<T1, int> {
  public:
  void foo() {
    cout << "T1, int" << endl;
  }
};
template<>
class A<int, int> {
  public:
  void foo() {
    cout << "int, int" << endl;
  }
};
template class A<float, int>;
template class A<int, int>;
// t.cpp
#include "t.h"
int main() {
  A<float, int> a;
  a.foo();  // no error
  A<int, int> a1; 
  a1.foo(); // undefined reference error, why?
  return 0;
}

编译命令是g++ t.cpp t2.cpp -o t,带有GCC 4.8.5。

您必须 sectare 中的部分和明确的专业化)。在这里,看起来像

template<class T> class A<T,int>;
template<> class A<int,int>;

主要模板后立即(避免任何可能发生错误隐式实例化的可能性。

编译器历史上一直对此"宽松",也就是说,有时它可以通过对所有源文件进行分析来实现您期望的。

您在此特定编译器中找到了这种意外"支持"的边缘。