Index

C & C++ Programming - Templates

// A template is not a class or a function.
// A template is a "pattern" that the compiler uses to generate a family of classes or functions.
// In order for the compiler to generate the code, it must see both the template definition
// (not just declaration) and the specific types/whatever used to "fill in" the template.
// For example, if you're trying to use a Foo, the compiler must see both the Foo template
// and the fact that you're trying to make a specific Foo.
// Your compiler probably doesn't remember the details of one .cpp file while it is compiling
// another .cpp file. BTW this is called the "separate compilation model."

#pragma once
template < typename T>
class Array {
public:
 Array(int len=10)
   : m_nLen(len)
   , m_tData(new T[len])
 { }
 ~Array()
 {    delete[] m_tData;
 }

 int Len() const;

 T const& operator[](int i) const
 {
   return m_tData[check(i)];
 }

 T& operator[](int i)
 {    return m_tData[check(i)];
 }

 Array(const Array&);
 Array& operator= (const Array&);

private:
 int m_nLen;
 T* m_tData;

 int check(int i) const
 {
   if (i < 0 || i >= m_nLen)
   throw BoundsViol("Array", i, m_nLen);
   return i;
 }
};

template < typename T>
int Array::Len() const
{
  return m_nLen;
}

//////////////////////////////////////////////////////////////////////////////////////////////
//
template < typename T>
class BigArray : public Array
{
public:
};

//////////////////////////////////////////////////////////////////////////////////////////////
//
template < typename T>
void swap(T& x, T& y)
{
  T tmp = x;
  x = y;
  y = tmp;
}

//////////////////////////////////////////////////////////////////////////////////////////////
//
void TestTemplate()
{
  Array < int > ai;
  Array < int > ai2(20);
  Array < float > af;
  Array < char* > ac;
  Array < std::string > as;
  Array < Array > aai;
}

Index