C++箴言:如何访问模板化基类中的名字
作者:sixth 来源:赛迪论坛 添加时间:2006-5-26 10:33:52假设我们要写一个应用程序,它可以把消息传送到几个不同的公司去。消息既可以以加密方式也可以以明文(不加密)的方式传送。如果我们有足够的信息在编译期间确定哪个消息将要发送给哪个公司,我们就可以用一个 template-based(模板基)来解决问题:
| class CompanyA { public: ... void sendCleartext(const std::string& msg); void sendEncrypted(const std::string& msg); ... }; class CompanyB { public: ... void sendCleartext(const std::string& msg); void sendEncrypted(const std::string& msg); ... }; ... // classes for other companies class MsgInfo { ... }; // class for holding information // used to create a message template class MsgSender { public: ... // ctors, dtor, etc. void sendClear(const MsgInfo& info) { std::string msg; create msg from info; Company c; c.sendCleartext(msg); } void sendSecret(const MsgInfo& info) // similar to sendClear, except { ... } // calls c.sendEncrypted }; |
这个能够很好地工作,但是假设我们有时需要在每次发送消息的时候把一些信息记录到日志中。通过一个 derived class(派生类)可以很简单地增加这个功能,下面这个似乎是一个合理的方法:
| template class LoggingMsgSender: public MsgSender public: ... // ctors, dtor, etc. void sendClearMsg(const MsgInfo& info) { write "before sending" info to the log; sendClear(info); // call base class function; // this code will not compile! write "after sending" info to the log; } ... }; |
站内搜索