Speed up development with full-stack environments for every branch.

Learn More

C++ Examples for Template specialization and partials

111 Runs 946 Views 259 Copies
Saved

Saved

tianxiasoft 13

tianxiasoft
published 4 years ago

#include <iostream>

using namespace std;

/******************************************************************************************/
/*  This example shows use of templates.  							                  */
/******************************************************************************************/

// Array class that has elements of type T
template <typename T>
class Array
{
private:
	// length of this array
	int m_nLength;
	// memory buffer of data
	T *m_ptData;

public:
	// constructor
	Array()
	{
		m_nLength = 0;
		m_ptData = 0;
	}

	// constructor that has length
	Array(int nLength)
	{
		// create buffer of size nLength
		m_ptData= new T[nLength];
		m_nLength = nLength;
	}

	// destructor
	~Array()
	{
		// release memory buffer
		delete[] m_ptData;
	}

	// erase all data
	void Erase()
	{
		delete[] m_ptData;
		// We need to make sure we set m_pnData to 0 here, otherwise it will
		// be left pointing at deallocated memory!
		m_ptData= 0;
		m_nLength = 0;
	}

	// operator function that retrieves the element of index nIndex
	T& operator[](int nIndex)
	{
		return m_ptData[nIndex];
	}

	// The length of the array is always an integer
	// It does not depend on the data type of the array
	int GetLength(); // templated GetLength() function defined below
};

// declare the GetLength function
template <typename T>
int Array<T>::GetLength() { return m_nLength; }

// main function
int main()
{
	// declare int array
	Array<int> anArray(12);
	// declare double array 
	Array<double> adArray(12);

	int nCount = 0;
	// set value for array
	for (; nCount < 12; nCount++)
	{
		anArray[nCount] = nCount;
		adArray[nCount] = nCount + 0.5;
	}
	// print the content of each array
	for (nCount = 11; nCount >= 0; nCount--)
		std::cout << anArray[nCount] << "\t" << adArray[nCount] << std::endl;

	cin.get();
	return 0;
}
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).