传递类型您也需要接受模板模板参数。CCD_ 13不使模板模板使用CCD_ 14和CCD_。它们只是用于文档,可以删除
因此,我需要制作一个mixin类,它将封装某个派生类的子类。派生类应该从mixin继承,同时提供容器模板作为mixin的模板模板参数。
所需的代码有点像:
/*template definition*/
template<template<typename T, typename A> class C>
class HasChildren {
protected:
C<T, A> m_children;
/* whatever */
};
它有一系列问题:
- 当试图像
HasChildren<std::vector<int>>
一样实例化这个类(只是为了测试(时,编译器会说expected a class template, got ‘std::vector<int>’
。很明显,我不是在传递模板模板我想知道我到底想通过什么 - 对于
C<T, A> m_children;
,编译器说T
和A
超出了范围。当我为它们添加typename
关键字时,错误变为error: wrong number of template arguments (1, should be 2)
我想知道为什么T
和A
超出范围,以及为什么添加typename
会导致此错误
std::vector<int>
而不是模板std::vector
示例:
template <template <class, class> class C, class T, class A>
// ^^^^^^^ ^^^^^^^
class HasChildren {
protected:
C<T, A> m_children;
};
int main() {
HasChildren<std::vector, int, std::allocator<int>> hc;
// ^template^ ^-----parameters-------^
}
如果您喜欢像最初尝试的那样实例化HasChildren
,通过使用HasChildren<std::vector<int>>
,您可以通过专门化HasChildren
:来实现这一点
template<class> class HasChildren; // primary
// specialization:
template<template <class, class> class C, class T, class A>
class HasChildren<C<T,A>> {
protected:
C<T,A> m_children;
};
int main() {
HasChildren<std::vector<int>> hc;
}