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

Learn More

C++ Examples for Templates in C++

602 Runs 3009 Views 418 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 <class 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 <class 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).