undefined引用完整模板特化类成员函数,但不是部分特化

问题描述 投票:3回答:1

所以当使用模板显式实例化与完全模板类专门化时,我得到一个未定义的引用错误,但问题是,部分模板类专业化顺利进行而没有错误。

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

提前致谢。

// 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++ templates template-specialization partial-specialization
1个回答
2
投票

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

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

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

编译器在历史上一直对此“松懈”,也就是说,有时它会对所有源文件的分析产生预期效果。

你已经在这个特定的编译器中找到了这种意外“支持”的优势。

© www.soinside.com 2019 - 2024. All rights reserved.