C++ examples for template:template class
A templatize vector class with an initializer list
#include <initializer_list> template <class T> class MyVector//from w ww. j a va 2 s . c om { public: MyVector(int nArraySize) { nSize = nArraySize; array = new T[nArraySize]; reset(); } MyVector(const std::initializer_list<T> il) :MyVector(il.size()) { // copy the contents of il into the vector for(const T* p = il.begin(); p < il.end(); p++) { add(*p); } } int size() { return nWriteIndex; } void reset() { nWriteIndex = 0; nReadIndex = 0; } void add(const T& object) { if (nWriteIndex < nSize) { array[nWriteIndex++] = object; } } T& get() { return array[nReadIndex++]; } protected: int nSize; int nWriteIndex; int nReadIndex; T* array; }; #include <cstdlib> #include <cstdio> #include <iostream> using namespace std; int main(int argc, char* pArgs[]) { MyVector<int> myVector = {10, 20, 30, 40, 50}; for(int i = 0; i < myVector.size(); i++) { cout << i << " : " << myVector.get() << "\n"; } return 0; }