条款43:学习处理模板化基类内的名称

来源:互联网 发布:mac hosts 修改 编辑:程序博客网 时间:2024/05/17 01:54
*条款43:学习处理模板化基类内的名称*/#include<iostream>#include<string>using namespace std;class CompanyA{//..void sendCleartext(const std::string&msg);//未加密void sendEncrypted(const std::string&msg);//已加密 //..};class CompanyB{public://..void sendCleartext(const string &msg);void sendEncrypted(const std::string&msg);};class MsgInfo{//这个类用来保存信息,以备将来产生信息//..};template<typename Company>class MsgSender{public://..void sendClear(const MsgInfo&info){string msg;//在这里,根据info产生信息Company c;c.sendCleartext(msg);}void sendSecret(const MsgInfo&info){//..类似sendClear,唯一不同是这里调用c.sendEncryted}};/*template<typename Company>class LoggingMsgSender:public MsgSender<Company>{//这时是想让每次送出信息时志记某些信息,子类可轻易加上这样的生产力, public://..void sendClearMsg(const MsgInfo& info){//将传送前的信息写至log//sendClear(info);//调用基类的函数,这段代码无法通过编译,原因在于,这里一个基于模板继承下来的子类,它虽然继承自MgSender<Company>,但其中的Company是个template参数,不到后来(loggingMsgSender被具现化),无法确切知道它是什么,就无法知道class MsgSender<Company>看起来像什么,更明确地说是没办法知道它是否有个senderClear函数//将传送后的信息写至log}};*///这里有一个坚持使用加密通读讯的类class CompanyZ{public://..void sendEncrypted(const std::string&msg);//..};//显示如果用MsgSender template 发CompanyZ并不合适(不用sendcleartext),这里提供了一个特化的版本template<>//一个全特化class MsgSender<CompanyZ>{//MsgSender,它和一般template相同,差别只是在于它删掉了Sendclearpublic:void sendSecret(const MsgInfo&info){//...}};//这个例子也说明了上,loggingMsgSender出现的原因,可能在模板参数不确定的时候,基类里甚至可能都不存在这个函数,它知道基类模板有可能被特化,而那个特化版本可能不提供和一般性template相同的接口,因此这往往气绝在模板化基类内寻找继承来崦的名称,也就是说当我们从ooc++ 跨进到 Template C++,继承就不像以前那般畅行无阻了。。//对于这种“模板化基类”的行为的解决方法如下://1 在基类函数调用动作之前加上“this->"//2 使用using 声明式//3 明白指出被调用的函数位于基类内template<typename Company>class LoggingMsgSender:public MsgSender<Company>{ public://../*using MsgSender<Company>::sendClear;//第二种方法:告诉编译器,请它假设sendClear位于基类内sendClear(info);*//*void sendClearMsg(const MsgInfo& info){this->sendClear(info);//成立,假设sendClear将被继承}*/// 第三种方法:void senderClearMsg(const MsgInfo&info){MsgSender<Company>::sendClear(info);//ok,假设sendClear将被继承下来。//但第三种方法是最不让人满意的解法,如果被调用的虚函数,上述明确资格修饰会关闭虚函数 的绑定行为 }};int main(){return 0;}

0 0