C ++: Definition and instantiation of class templates


Class template definition format

template<class T1, class T2, ..., class Tn> 
class 类模板名
{
// 类内成员定义 
};

Use class templates to build dynamic sequence tables

template <class T>
class SeqList {
	T* m_data;
	size_t m_size;
	size_t m_capacity;

	void checkCapacity();
public:
	SeqList(size_t size = 0, size_t capacity = 10) :
		m_data(new T[capacity]),
		m_size(size),
		m_capacity(capacity)
	{
	}

	T& operator [](size_t i)
	{
		return m_data[i];
	}

	void push_back(const T& src);
	void pop_back();

	int size();

	~SeqList();
};

// 在类中声明,在类外定义。 
// 注意:类模板中函数放在类外进行定义时,需要加模板参数列表
template <class T>
void SeqList<T>::checkCapacity() {
	if (m_size == m_capacity) {
		m_capacity *= 2;

		m_data = (T*)realloc(m_data, sizeof(T) * m_capacity);
		/*T* newSpace = new T[m_capacity];

		for (i = 0; i < m_size; i++) {
			newSpace[i] = m_data[i];
		}
		delete[] m_data;
		m_data = newSpace;*/
	}
}

template <class T>
void SeqList<T>::push_back(const T& src) {
	checkCapacity();

	m_data[m_size++] = src;
}

template <class T>
void SeqList<T>::pop_back() {
	if (m_size == 0) {
		return;
	}
	m_size--;
}

template <class T>
int SeqList<T>::size() {
	return m_size;
}

template <class T>
SeqList<T>::~SeqList() {
	if (m_data) {
		delete[] m_data;
	}
	m_size = m_capacity = 0;
}

Note: SeqList is not a specific class, it is a mold that the compiler generates a specific class based on the type being instantiated

Class template implementation remember:

  1. In the process of class template implementation, it is best not to split the class and function implementation into two files. Directly complete the function implementation and class in the .h file.

  2. If split into two files, both files must be included in the main function file, otherwise the corresponding implementation code cannot be found, and a physical version of the executable function cannot be generated.

Instantiation of class templates

Class template instantiation is different from function template instantiation. Class template instantiation needs to be followed by <> after the name of the class template, and then the type of instantiation can be placed in <>. The name of the class template is not the real class, but instantiated The result is the real class.

Code example:

int main(){ 
	// SeqList类名,SeqList<int>才是类型 
	SeqList<int> sl;

	sl.push_back(1);
	sl.push_back(2);
	sl.push_back(3);
	sl.pop_back();
	SeqList<double> s1;
	s1.push_back(3.1415);
	s1.push_back(1.618);
	for (int i = 0; i < sl.size(); ++i)
	{
		cout << sl[i] << " ";
	}
	cout << endl;
	for (int i = 0; i < s1.size(); ++i)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	return 0;
}

Code generation diagram
Insert picture description here


If you have different opinions, please leave a message to discuss

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/104914248