Template parameter

Default type parameter

Function parameters can be set to a default value. We can now set a default type for class template type parameters.

Specifies that the default type argument of the generic Stack is int

template<typename T = int>
class Stack{
  ...
};
Copy the code

When we define an object like this:

Stack<> stack;
Copy the code

By default, or implicitly, a Stack object is instantiated.

The advantage is that once the default type is specified, the user does not have to write it.

Untyped parameter

Use non-type parameters in template prefixes. When instantiating a template, non-type arguments should be objects. As follows:

template<typename T, int capacity>
class Stack {.private:
	T elements[capacity];
	int size;
};
Stack<char.100> charStack;
Copy the code

As in STD array initialization: STD ::array

; This is true when non-type arguments are objects, except for primitive data types;
,100>

template<typename T, Color c>
class Label {. };Color color(0.0.255);
Label<char,color> label;
Copy the code

Note that the default values of the parameters must be on the far right, of course we can define all the default values, then there will be no problem. Note that the declaration of template member functions also needs to be changed. Here it is:

/ / generics
template <typename T = char.int N = 100>
// Write StackOfIntegers
class Stack {
private:
	T elements[N];
	int size{ 0 };
public:
	bool empty(a);
	T peek(a);
	T push(T value);
	T pop(a);
	int getSize(a);
	Stack(a); };template <typename T, int N>
Stack<T,N>::Stack() {
	size = 0;
	for (auto& i : elements) {
		i = 0; }}Copy the code

Template inheritance

A few principles for template inheritance:

Common classes can be inherited from class template instances. A template is instantiated as a class, and classes can be inherited from one another. A template can inherit from a common class. A class template can inherit from a class template

That is, a class cannot inherit from one template, and all three combinations are possible.

When and where to use templates

Similar processing of different types of data (algorithms, containers, traversals, etc.) when using a template library written by someone else

OOP or GP

Generic programming is widely used in C++, often replacing object-oriented programming. Almost the entire C++ standard library relies on generic programming. Inheritance and runtime polymorphism are used sparingly in the C++ standard library. More inheritance is used in exceptions, strings, and IO streams.