能对默认模板参数传递做一个例子吗
时间: 2023-08-06 08:06:54 浏览: 52
当定义一个模板时,可以为其中的一个或多个模板参数指定默认值,以便在使用模板时,如果某个参数没有显式地传递,就可以使用默认值。
以下是一个使用默认模板参数的例子,其中定义了一个模板类`MyVector`,它有两个模板参数,分别是元素类型和分配器类型。默认情况下,元素类型为int,分配器类型为std::allocator:
```c++
#include <iostream>
#include <vector>
#include <memory>
template <typename T, typename Allocator = std::allocator<T>>
class MyVector {
public:
MyVector() {
std::cout << "MyVector constructor" << std::endl;
}
private:
std::vector<T, Allocator> data_;
};
int main() {
MyVector<int> v;
return 0;
}
```
在上面的例子中,我们使用`MyVector<int>`来实例化模板类`MyVector`,没有传递分配器类型,因此使用默认值std::allocator<int>。运行程序,输出结果为:
```
MyVector constructor
```
如果需要传递自定义的分配器类型,可以显式指定第二个模板参数:
```c++
int main() {
MyVector<int, std::allocator<char>> v;
return 0;
}
```
在上面的例子中,我们使用`MyVector<int, std::allocator<char>>`来实例化模板类`MyVector`,显式地传递了分配器类型std::allocator<char>。运行程序,输出结果为:
```
MyVector constructor
```
通过默认模板参数传递,可以使模板更加灵活,更易于使用。