使用模板类进行模板专门化

Template specialization with template class

本文关键字:专门化      更新时间:2023-10-16

我做了以下事情。

template <class C> class B{};
template <class X> 
struct  A{
  int member;
};
template <class Y> 
struct  A<B<Y>>{
    A(int n):member(n){}
};
int main(int, char**){}

。类X可能是模板本身,在这种情况下,我想对类A模板进行专门化。
但是编译器说:

d:>g++ -std=gnu++11 -o spec.exe spec.cpp
spec.cpp: In constructor 'A<B<Y> >::A(int)':
spec.cpp:11:14: error: class 'A<B<Y> >' does not have any field named 'member'  

如果A<B<Y>>类与A类完全分离,则一切正确,可能没有A类的任何成员。但我想要A专业化。和它所有的内容。
或者,当XB<Y>时,可能是A的特定构造函数。
如何实现?

模板特化是一种完全不同于继承的机制。它不扩展一般模板的内容:它用特殊化用例的新内容替换它们。所以编译器是正确的:您的类A<B<Y>>没有任何名为member的字段。它只有一个构造函数,它接受一个int和一些额外的自动生成的函数(复制构造函数,析构函数等)。

如果你想"继承"模板的内容,你有两个选择:

  • 将模板中的所有内容复制到专门化
  • 将公共内容放在基类中并从它继承

根据你想要做的事情,这些选项中的一个会比另一个更好。

实现方法:

template <class C> class B{};
template <class X>
struct  A{
  int member;
};
template <class Y>
struct  A<B<Y> >{ // A<
    int member;  // just add member here
    A(int n):member(n){}
};

当你实现模板专门化时,就好像你定义了一个全新的类。
我猜你正在寻找的是成员函数专门化,但这个不支持部分专门化,如果你试图专门化一个给定模板类的构造函数,那么这个构造函数必须隐式声明。
template <class C> class B{};
template <class X>
struct  A{
  A(int n); // I implicitly-declared the constructor that I want to specialize. 
            // you can still define it if you want.
  int member;
};
// this is the contructor specialization,
// Note this isn't partial specialization, it's explicit specialization so you
// must provide a type that you want to specialize it with, in this case B<int>
template <>
A<B<int> >::A(int n):member(n){}