模板类模板参数
这个语法是一个模板类模板参数(template template parameter),意味着在一个类模板中,可以指定一个类模板作为参数,这个参数的实例化需要传递一个类型参数。例如:
template <typename T>
class MyVector {
// ...
};
template <template <typename> class Container>
class Wrapper {
Container<int> data;
// ...
};
int main() {
Wrapper<MyVector> wrapper; // MyVector<int> 会作为 Container<int> 的实例
// ...
}
在这个例子中,Wrapper
是一个类模板,它有一个模板类模板参数 Container
,这个参数本身是一个模板类,但是它只接受一个类型参数 T
。在 Wrapper
类中,我们可以使用 Container<int>
来实例化模板类模板参数,并使用它的成员变量和成员函数。当我们使用 MyVector
作为模板类模板参数时,需要显式指定模板参数类型,即 Wrapper<MyVector>
,这会导致 MyVector<int>
作为 Container<int>
的实例化类型被传递给 Wrapper
类模板。
模板类模板参数,举例子
模板类模板参数可以用来定义一个模板类,其模板参数是一个模板类。例如,以下是一个使用模板类模板参数的示例:
#include <iostream>
#include <vector>
#include <list>
template <typename T, template <typename> class Container>
class Stack {
public:
void push(const T& value) {
container.push_back(value);
}
void pop() {
container.pop_back();
}
T& top() {
return container.back();
}
bool empty() const {
return container.empty();
}
private:
Container<T> container;
};
int main() {
Stack<int, std::vector> s1;
s1.push(1);
s1.push(2);
s1.push(3);
while (!s1.empty()) {
std::cout << s1.top() << " ";
s1.pop();
}
std::cout << std::endl;
Stack<int, std::list> s2;
s2.push(4);
s2.push(5);
s2.push(6);
while (!s2.empty()) {
std::cout << s2.top() << " ";
s2.pop();
}
std::cout << std::endl;
return 0;
}
这个示例定义了一个 Stack
模板类,其包含两个模板参数:T
和 Container
。其中,Container
是一个模板类模板参数,它被用于存储元素。在 push
函数中,我们可以调用 container.push_back(value)
来向容器中添加元素。在 main
函数中,我们实例化了两个 Stack
类型的对象,其中一个使用 std::vector
作为容器,另一个使用 std::list
作为容器。
总的来说
总结:可以想象stack,queue等容器适配器,他们就是模板类模板参数,他们是wrapper,里面有container。