使用模板进行类声明
class declaration with template
本文关键字:声明 更新时间:2023-10-16
>我有两个类,它们以不同的方式定义,如下所示:
template<class T, size_t N = 100> class Stack {
T data[N];
};
template<class T = int, size_t N = 100> // Both defaulted
class Stack {
T data[N];
};
我想知道这是定义类的两种不同方式,还是它们有不同的含义?
您的第一个Stack
类没有第一个模板参数的默认值:
template<class T, size_t N = 100>
使用此类,可以声明如下Stack
:
Stack<int> stack; // You have to provide at least 1 template parameter
Stack<int, 50> stack;
第二个Stack
类的第一个模板参数的默认值为 int
:
template<class T = int, size_t N = 100>
使用此 Stack
类,可以声明如下Stack
:
Stack<> stack; // You can declare a Stack with no template parameters
Stack stack; // The same, but C++17-only
Stack<int> stack;
Stack<int, 50> stack;
第二个版本具有默认模板参数值 int
。换句话说,在创建对象Stack
时不一定需要指定T
。
Stack s; // Ok. Internal array will be 'int data[100]'.
Stack<double> s2; // Template parameter overrides default value, i.e. 'double data[100]'.
对于第一个版本,上述内容无法编译,因为需要指定T
。
现场示例
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别