首页 > 解决方案 > 未定义对完整模板特化类成员函数的引用,但不是部分特化

问题描述

所以当使用具有完整模板类专业化的模板显式实例化时,我得到了一个未定义的引用错误,但问题是,部分模板类专业化运行良好,没有错误。

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

提前致谢。

// 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。

标签: c++templatestemplate-specializationpartial-specialization

解决方案


您必须在使用它们的每个翻译单元中声明 部分式特化(在任何会隐式实例化该特化的使用之前)。在这里,看起来像

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

紧跟在主模板之后(以避免任何错误的隐式实例化的可能性。

历史上,编译器对此一直“松懈”,也就是说,有时它会按照您对所有源文件的分析所期望的那样做。

您已经在这个特定的编译器中发现了这种意外“支持”的优势。


推荐阅读