使用模板类进行模板专门化
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
专业化。和它所有的内容。
或者,当X
为B<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){}
相关文章:
- 是否可以对零模板参数进行模板专门化
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何基于模板化类的基类专门化成员函数
- 如何为指向复杂值的迭代器专门化算法?
- 专门化模板覆盖函数/避免对象切片
- 我能否根据其运算符()的签名专门化可变参数模板参数
- 如何使用模板化类专门化模板化函数?
- 线程 std::调用未知类型,无法专门化函数错误
- 输入两个不专门化大小的矩阵
- 如何在模板类中专门化赋值运算符?
- 如何专门化容器和枚举的模板
- Clang拒绝类模板的嵌套类仅通过专门化定义的代码是正确的吗
- 取消专门化C++模板参数
- SFINAE的变分变量模板专门化
- 如何在编译时专门化大型模板函数中的小部分
- 如何在c++运算符()中专门化调用模板
- 模板函数,其中一个参数需要专门化,而另一个不需要
- 如何专门化字符串数组的模板?
- 如何专门化模板
- 如何避免为模板化迭代器的每个可能的实例化专门化iterator_traits?