使用模板进行类声明

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

现场示例