Templates and Containers
Why template?
Template reuses source code. The container holds an unspecified parameter. When using a template, the parameter is substituted by the compiler.case from the book Thinking in C++.
template<class T> class Array { enum { size = 100 }; //static const int size = 100; T A[size]; public: T& operator[](int index) { if ( index < 0 and index >= size ) cout << "Index out of range" << endl; return A[index]; } };
Note:
template<class T>
means that T is the substitution parameter, and it represents a type name.Note the use of
enum {size = 100}
. It won't work if I use the following:int size = 100; /* Got the following warning and error: warning: in-class initialization of non-static data member is a C++11 extension [-Wc++11-extensions] int size = 100; ^ error: invalid use of non-static data member 'size' T A[size]; ^~~~ */
The following also doesn't work.
static int size = 100; /* Got the following error: error: non-const static data member must be initialized out of line static int size = 100; */
But the following works:
static const int size = 100;
Why:
In older versions of C++,
static const
was not supported inside classes. This meant that const was useless for constant expressions inside classes. However, people still wanted to do this so a typical solution (usually referred to as the “enum hack”) was to use an untaggedenum
with no instances. An enumeration must have all its values established at compile time, it’s local to the class, and its values are available for constant expressions. Thus, you will commonly see:class Bunch { enum { size = 1000 }; int i[size]; };
Also note that in such a way the array uses the memory in stack instead of heap. [If
new
is used when declaring the array, the memeroy is from the heap memory.]