Template Overview
To gain some perspective, let's begin with a general example that shows how templates work. We'll explain concepts from the example throughout the section, though you'll probably follow this without difficulty now:
#include <iostream>
#include <rw/cstring.h>
#include <rw/tvdlist.h>
int main()
{
// Declare a linked list of strings
RWTValDlist<RWCString> stringList;
RWCString sentence;
// Add words to the list
stringList.insert("Templates");
stringList.insert("are");
stringList.insert("fun!");
// Now use standard iterators to build a sentence
RWTValDlist<RWCString>::const_iterator iter = stringList.begin();
if (iter != stringList.end()) {
sentence.append(*(iter++));
}
while (iter != stringList.end()) {
sentence.append(" ");
sentence.append(*(iter++));
}
// Display the result
std::cout << sentence << std::endl;
return 0;
}
Output:
Templates are fun!
The preceding example demonstrates the basic operation of templates. Using the collection class template RWTValDList, we instantiate the object stringList, simply by specifying type RWCString. The template gives us complete flexibility in specifying the type of the list; we don't write code for the object, and the Essential Tools Module does not complicate its design with a separate class RWTValDListofRWCString. Without the template, we would be limited to types provided by the program, or forced to write the code ourselves.