1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
When an existing class template is used as a base class for deriving an
ordinary class, the class template parameters are specified when defining the
derived class's interface. If in a certain context an existing class template
lacks a particular functionality, then it may be useful to derive an ordinary
class from a class template. For example, although the class tt(map) can
easily be used in combination with the tt(find_if()) generic algorithm
(section ref(FIND)), it requires the construction of a class and at least
two additional function objects of that class. If this is considered too much
overhead then extending a class template with tailor-made functionality
might be considered.
Example: a program executing commands entered at the keyboard might accept all
unique initial abbreviations of the commands it defines. E.g., the command
tt(list) might be entered as tt(l, li, lis) or tt(list). By deriving a class
tt(Handler) from
verb( map<string, void (Handler::*)(string const &cmd)>)
and by defining a member function tt(process(string const &cmd)) to do the
actual command processing a program might simply execute the following
tt(main()) function:
verbinclude(//MAIN examples/template2concrete.cc)
The class tt(Handler) itself is derived from a tt(std::map), in which
the map's values are pointers to tt(Handler)'s member functions, expecting the
command line entered by the user. Here are tt(Handler)'s characteristics:
itemization(
it() The class is derived from a tt(std::map), expecting the command
associated with each command-processing member as its keys. Since
tt(Handler) uses the map merely to define associations between
hi(inheritance: private derivation) the commands and the processing
member functions and to make tt(map)'s types available, private derivation is
used:
verbinclude(//HEAD examples/template2concrete.cc)
it() The actual association can be defined using static private data
members: tt(s_cmds) is an array of tt(Handler::value_type) values, and
tt(s_cmds_end) is a constant pointer pointing beyond the array's last element:
verbinclude(//STATIC examples/template2concrete.cc)
it() The constructor simply initializes the map from these two static data
members. It could be implemented inline:
verbinclude(//CONS examples/template2concrete.cc)
it() The member tt(process) iterates along the map's elements. Once the
first word on the command line matches the initial characters of the command,
the corresponding command is executed. If no such command is found, an error
message is issued:
verbinclude(//PROCESS examples/template2concrete.cc)
)
|