typedef syntax to get started on the template.
You'll be making a template allowing you to create
a table mapping strings to ints, ints to strings, ints to Robots, or
whatever. The main rule is that the indexing class must have
the comparators <, >,
and ==.
StringToIntTable.cc and
StringToIntTable.h and give them more appropriate (and
general) names like, Table.cc and Table.h.
StringToIntTable with
Table in all files.
= 0 in the class declaration of
Table. (Dealing with this optional argument in
templates is a bit anoying.) Be sure you never assigned the initial
value of = 0 in your code. To get your code to compile,
you'll need to change the declaration at the top of main to:
Table table(0);
typedef's. One will be the Key
(currently of class string), and one will be the
Data (currently of class int). For reference, you
may wish to look at the List class definitions from class in
~mc38/labs/operator-overloading/files/List.*Be sure the code compiles and runs.
#include <iostream>
#include <string>
#include "Table.h"
int main() {
Table table (" 0 ");
table[20] = " 1 ";
table[10] = " 2 " ;
table[-100] = " 3 ";
table[10] = " 4 ";
table[-100] = " 5 ";
cout << table[20] << table[10] << table[-100] << table[30] << endl;
return 0;
}
List
class is in the directory ~mc38/labs/templates/list/. A
few things are worth noting.
Table.h and Table.cc files will
need to be edited. Any program using these classes will need to be
changed only slightly.
<typename Key, typename Data>
List.h file ends with the lines
#include "List.cc" #endif LIST_H
template<typename ListItem>Both the
List class and the Node class are templated.
List<ListItem>::methodName
Node or List variable declaration
(whether they be parameters, local variables or instance variables) is
replaced by the template:
Node<ListItem> varName List<ListItem> varName
Makefile so that it no longer compiles
Table.cc. Only your file with your main should
be compiled.
Table<int, string> table (" 0 "); // and
Table<string, int> table (" 0 ");
stream I/O from Chapter 10.
There is one thing that is very annoying about the process of writing a
typedef class before writing a template.
What if you want to enhance the templated class? You are stuck with
two choices: Either (1) Change the typedef class and
reconvert it, or (2) change the template class and hope
you can debug it.
Write a program to help automate this process. Your program will take
a class you've designed with typedef and change it to a
templated class. Since you will just use this for your own programs,
you can make any assumptions you want to in order to make your task a
bit easier. For example, you could assume that the
typedef's appear at the top of the .h file.
Or you could assume that the typedef takes only
one argument.
The right way to do this is using Linux string processing
tools such as awk. If you know something about these
tools already, you are free to use them.