繁体   English   中英

模板专业化与模板类

[英]Template specialization with template class

我做了以下事情。

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){}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM