模板模板参数(Template Template Parameter),简单说就是:让模板参数本身也是一个模板。
通常情况下,我们传的是类型(如int)或常量值(如10)。而模板模板参数允许你传入一个类模板(如std::vector或std::list),然后再用你的类型去实例化它。
这在你需要“容器适配”时特别有用——比如你想定义一个容器包装器,把具体的容器类型(vector/list/deque)作为参数传进去,同时把元素类型也留给用户指定。
核心语法解析
声明方式:
template <typename T, template <typename...> class ContainerType>typename T:普通类型参数,指定元素类型。template <typename...> class ContainerType:模板模板参数,表示ContainerType本身是个模板(可接受任意多个类型参数)。
C++17之前必须用
class关键字,不能用typename;C++17及之后两者都可
#include <iostream> #include <vector> #include <list> #include <string> // T: 元素类型 // ContainerType: 模板模板参数,代表一个容器模板(如 vector, list) template <typename T, template <typename...> class ContainerType> class MyWrapper { private: ContainerType<T> storage; // 使用 T 去实例化传入的容器模板 public: // 添加元素 void add(const T& value) { storage.push_back(value); } // 打印所有元素 void print() const { for (const auto& val : storage) { std::cout << val << " "; } std::cout << std::endl; } }; int main() { // 1. 使用 std::vector 作为底层容器,元素类型为 int MyWrapper<int, std::vector> vecWrapper; vecWrapper.add(10); vecWrapper.add(20); vecWrapper.add(30); std::cout << "Vector 中的内容: "; vecWrapper.print(); // 输出: 10 20 30 // 2. 使用 std::list 作为底层容器,元素类型为 std::string MyWrapper<std::string, std::list> listWrapper; listWrapper.add("Hello"); listWrapper.add("World"); std::cout << "List 中的内容: "; listWrapper.print(); // 输出: Hello World return 0; }