Defining Class Templates - C++ template

C++ examples for template:template class

Introduction

A class template is prefixed by the template keyword followed by the parameters for the template between angled brackets.

The general form of a class template looks like this:

template <template parameter list>
class ClassName
{
  // Template class definition...
};

ClassName is the name of this template.

To create a class from a template, you must specify arguments for every parameter in the list.

A Simple Class Template

template <typename T>
class Array
{
  // Definition of the template...
};

Implement the body of a template class.

template <typename T>
class Array
{
private:
  T* elements;                              // Array of type T
  int size;                              // Number of array elements

public:
  explicit Array<T>(int arraySize);      // Constructor
  Array<T>(const Array<T>& array);          // Copy Constructor
  ~Array<T>();                              // Destructor
  T& operator[](int index);              // Subscript operator
  const T& operator[](int index) const;  // Subscript operator-const arrays
  Array<T>& operator=(const Array<T>& rhs); // Assignment operator
};

Related Tutorials