The code below illustrates the usage of template-template parameters. The MyCollections class template creates an internal collections of items of type T. The type of the collection (vector, list etc.) is determined by its template-template parameter Collection.

When considering the functional language metaphor (i.e: Types in template programming are equivalent to values in functional programming), a template-template parameter is the equivalent of a function in functional programming.


Compatibility:

#include <iostream>
#include <stdexcept>
#include <vector>
#include <list>

using namespace std;



template<typename T, template <typename S> class Collection>
class MyCollection 
{
private:
   typedef Collection<T> Items;
   Items items_;        

public:
   void add(T const& t) 
   { 
      items_.push_back(t); 
   }
    
   T get(int index) const
   {
      typedef typename Items::const_iterator Iter;
      for(Iter i = items_.begin(); i != items_.end(); ++i, --index)
      {
         if(index == 0)
            return *i;
      }

      throw runtime_error("Index out of bounds");
   }

   void clear()
   {
      items_.clear();
   }

   int size() const
   {
      return items_.size();
   }
};

int main(int argc, char* argv)
{
   MyCollection<int,vector> integers;
   integers.add(3); 
   integers.add(4);
   integers.add(5);

   cout << integers.get(0) << ',' << integers.get(1) << ',' 
      << integers.get(2) << endl;

   MyCollection<string,list> strings;
   strings.add("three"); 
   strings.add("four");
   strings.add("five");

   cout << strings.get(0) << ',' << strings.get(1) << ',' 
      << strings.get(2) << endl;

   return 0;
}