subhasmita panda
subhasmita panda

Reputation: 33

class declaration with template

I have two classes that are defined in different ways like below:

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]; 
};

I want to know if these are two different ways to define a class, or do they have a different meaning?

Upvotes: 1

Views: 75

Answers (2)

Felix Glas
Felix Glas

Reputation: 15524

The second version has a default template parameter value int. In other words, T don't necessarily needs to be specified when creating an object Stack.

Stack s; // Ok. Internal array will be 'int data[100]'.
Stack<double> s2; // Template parameter overrides default value, i.e. 'double data[100]'.

With the first version, the above wouldn't compile as T needs to be specified.

Live example

Upvotes: 1

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

Your first Stack class has no default value for the first template parameter:

template<class T, size_t N = 100>

With this class, you can declare a Stack like this:

Stack<int> stack; // You have to provide at least 1 template parameter
Stack<int, 50> stack;

Your second Stack class has a default value of int for the first template parameter:

template<class T = int, size_t N = 100>

With this Stack class, you can declare a Stack like this:

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;

Upvotes: 1

Related Questions