1. When switching from "Object-Oriented C ++" to "template C ++", inheritance may encounter problems:Because the base class template may be made special, and the specific version may change the Member, C ++ refuses to search for the inherited name in the templated base class.
2. Example: assume that the information is transmitted to different companies. The transmission methods include plaintext transmission and ciphertext transmission. The template design method is used:
Template <typename company> class msgsender {public :... void sendclear (const msginfo & info) {STD: String MSG ;... // generate Company C; C. sendcleartext (MSG);} void sendsecret (const msginfo & info ){...} // encrypted transfer };
If you want to add the function of recording information when sending information, use the inheritance method:
Template <typename company> class loggingmsgsender: Public msgsender <company> {public :... void sendclearmsg (const msginfo & info ){... // write the information before transfer to the record information sendclear (Info); // try to call the base class member function to complete sending, but cannot pass compilation. This is because you do not know the type of company when the derived class is not activated, so you do not know whether the function exists in the base class... // write the transferred information to record information }...};
Improvement Method:
(1) Add the this pointer before the base class function calls the action:
This-> sendclear (Info); // assume that the function is inherited
(2) Use the using declarative class to use the base class namespace:
Using msgsender <company>: sendclear; // tells the compiler to make it assume that the base class contains sendclear
(3) explicitly specifying that a function is a function in the base class:
Msgsender <company >:: sendclear (Info); // assume that the function is inherited
3. if a class is similar to a template class, but its structure is different, you can use "Fully-exclusive template". In this way, when the template is specially converted to a specific template parameter type, the special version is called, definition Format:
Template <> class msgsender <companyz> {// This version is public when the parameter is of the companyz type :... void sendsecret (const msginfo & info); // a specific version ...};