模板参数

类型参数

类型参数用于表示任意类型,在模板实例化时被具体的类型替代

1
2
3
4
template<typename T>
T add(T n1, T n2) {
return n1 + n2;
}

非类型参数

非类型参数允许模板接受非类型的值,如整数、指针或引用。

1
2
3
4
template<size_t N = 10>
void Print() {
cout << N << endl;
}

C++17 新增支持 auto ,可以不必写明非类型参数的实际类型,可见灵活性更强了。

1
2
3
4
template<auto N = 10>
void Print() {
cout << N << endl;
}

模板模板参数

允许模板接受另一个模板作为参数。这对于抽象容器和策略模式等场景非常有用。

1
2
3
4
5
6
7
8
9
template <template <typename, typename> class Container, typename T>
class ContainerPrinter {
public:
void print(const Container<T, std::allocator<T>>& container) {
for(const auto& elem : container)
std::cout << elem << " ";
std::cout << std::endl;
}
};

可以看到,模板模板参数也并不难理解,如果我们声明一个类模板:

1
2
template<typename T,typename U>
class Container;

至于模板模板参数中的为什么没有写出 T 和 U,而是只写了 typename。那是因为没有必要,会在实际应用的时候添加上,故而暂时省略。

等到你真用到,再添加:

1
void print(const Container<T, std::allocator<T>>& container);