Simple template classes in C++
posted on: 2010-06-18 22:30:25
This week I will be demonstrating how to use template classes in C++. Template classes should be used when you need functions and classes to use generic types. As always source code and binary are available at the bottom of the page.
One thing to remember when using template classes is that you should put your template class declaration and implementation in the same file (that is to say you cannot split the code between a .cpp and .h). Otherwise you will find yourself with undefined reference errors when you build errors with some compilers.
The typename is a keyword that is used with template classes. typename indicates to the compiler to treat the following declaration as a type, otherwise there would be compilers errors as the compiler would take T to be a class and not a type.
The contents of collector.h, my template class
#include <iostream>
#include <vector>
template <typename T>
class Collector
{
public:
void Add(T const &);
void RemoveFirst();
void RemoveLast();
void Render();
private:
std::vector<T> m_localVectorData;
};
template <typename T> void Collector<T> ::Add(T const &d)
{
this->m_localVectorData.push_back(d);
}
template <typename T> void Collector<T>::RemoveFirst()
{
this->m_localVectorData.erase(this->m_localVectorData.begin( ), this->m_localVectorData.begin( )+1);
}
template <typename T> void Collector<T>::RemoveLast()
{
this->m_localVectorData.erase(this->m_localVectorData.end( )-1, this->m_localVectorData.end( ));
}
template <typename T> void Collector<T>::Render()
{
typename std::vector<T>::iterator iter;
for (iter = this->m_localVectorData.begin( ); iter != this->m_localVectorData.end( ); iter++) {
std::cout << *iter << std::endl;
}
}
The contents of main.cpp
#include <stdio.h>
#include "Collector.h"
int main(int argc, char **argv)
{
Collector<int> intCollector;
intCollector.Add(1);
intCollector.Add(2);
intCollector.Add(3);
Collector<std::string> stringCollector;
stringCollector.Add("Dave");
stringCollector.Add("Nicholas");
stringCollector.Add("foobar");
std::cout << "*** Render Collectors ***" << std::endl;
intCollector.Render();
stringCollector.Render();
std::cout << "*** Remove first element from Collectors ***" << std::endl;
intCollector.RemoveFirst();
stringCollector.RemoveFirst();
intCollector.Render();
stringCollector.Render();
std::cout << "*** Remove last element from Collectors ***" << std::endl;
intCollector.RemoveLast();
stringCollector.RemoveLast();
intCollector.Render();
stringCollector.Render();
return 0;
}
Here is the source code as usual. I hope you have found this tutorial useful as usual please forward me with any questions.














