编译器找不到专门的 class 模板

Compiler cannot find specialized class template

我想使用部分模板专业化,但似乎缺少了一些东西。 这是我尝试过的:

template<class T1, class T2>
class AClass {};

template<class T>
class AClass<T, T> {}; // specialized class.

AClass<int,float> aClassIntFloat; // works just fine

AClass<int, int> aClassIntInt; // works just fine

AClass<int> specializedIntClass; //"error: wrong number of template arguments (1, should be 2)"

我错过了什么?

首先,您已经成功定义了部分专业:

  • AClass<int, int> 将用 T=int
  • 实例化 class AClass<T, T>
  • AClass<int,float> 将使用 T1=int 和 T2=float
  • 实例化 class AClass<T1, T2>

您可以通过添加 public 测试方法并为 aClassIntFloataClassIntInt (online demo) 调用它来轻松检查这一点。您会发现将使用为两个相同类型定义的偏特化。

你也可以再进行偏特化,例如:

template<class T2>
class AClass<double, T2>  { public: void test(){cout<<"ADT2"<<endl;}};

AClass<double, int> aClassDoubleInt; // works also fine

A partial specialization lets you fix some parameters but not all. But in the end, your template requires two parameters, and you'll have to provide two parameters. The only question is which specialization if any gets instantiated (online demo).