Using Template Classes to Handle Generic Data Types in STL Containers

A code snippet with which utilizes both template classes and STL to handle generic data types. In keeping with the spirit of this blog, I have kept the explanation to a minimum and hopefully the code posted below should be self-explanatory.  The idea is for readers to get the gist of what I am saying so that they can go off and make up more relevant examples of their own.

This Store class introduces the idea of template specialisation, so that user can create algorithms and containers handling any arbitrary data type eg strings, ints etc. Making further specialisation is a simple matter of changing the type declaration in the Store class.  This code also make uses of the generic string making class make_string described in a previous post in order to generate the string equivalenets of arbitrary data types.

#include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>

using namespace std;

// Generic string-making class for handling arbitrary data types
class make_string
{
public:
   template <typename T>
   make_string& operator<<( T const & datum )
   {
      buffer_ << datum;
      return *this;
   }
   operator string () const
   {
      return buffer_.str();
   }
private:
   ostringstream buffer_;
};

template< typename T >
class Store
{
private:
	vector< T > store;

public:
	void Add( T& v );
	void Print();
};

// Add container items
template< typename T>
void Store< T >::Add( T& v )
{
	store.push_back( v );
}

// Print container items
template< typename T>
void Store< T >::Print()
{
	vector< T >::iterator it = store.begin();

	for ( ; it != store.end(); ++it )
	{
		T v = (*it);
		string str = make_string() << v;
		cout << str << endl;
	}
}

void main()
{
	string strs[] = { "Hello", "World" };
	int vals[] = { 1, 2, 3, 4, 5 };

	// string handling
	Store<string> st_str;
	st_str.Add( strs[ 0 ] );
	st_str.Add( strs[ 1 ] );
	st_str.Print();

	// integer handling
	Store<int> st_int;
	for ( int i = 0; i < 5; i++ )
	{
		st_int.Add( vals[ i ] );
	}
	st_int.Print();
}

Giving the following output:




Leave a Reply