C++箴言:如何访问模板化基类中的名字 (3)
上一篇 /
下一篇 2008-05-04 13:52:02
已知 MsgSender 针对 CompanyZ 被特化,再次考虑 derived class(派生类)LoggingMsgSender:
ITPUB个人空间/M&u
XtNE
nITPUB个人空间4HG(q.u@template MJ;m3N(S2l(|0class LoggingMsgSender: public MsgSender{ITPUB个人空间U$lwF%O public:ITPUB个人空间-n{F@ \6wJ4J(g ...ITPUB个人空间"By)EP'|_V:qB void sendClearMsg(const MsgInfo& info) )bd/@I/C DUc0 {ITPUB个人空间A*T&|k
i%s write "before sending" info to the log;ITPUB个人空间'Ty]6~PIgx;P sendClear(info); // if Company == CompanyZ, Wkap/s)P4B6Z0 // this function doesn't exist!ITPUB个人空间({)?4T,Cp:F write "after sending" info to the log;ITPUB个人空间{;_9DQLX)o }ITPUB个人空间;?I/Th\A ... Q
~0?2R%S{z*f
E0}; |
ITPUB个人空间
W$qv]$hVf 就像注释中写的,当 base class(基类)是 MsgSender时,这里的代码是无意义的,因为那个类没有提供 sendClear function(函数)。这就是为什么 C++ 拒绝这个调用:它认可 base class templates(基类模板)可以被特化,而这个特化不一定提供和 general template(通用模板)相同的 interface(接口)。结果,它通常会拒绝在 templatized base classes(模板化基类)中寻找 inherited names(继承来的名字)。在某种意义上,当我们从 Object-oriented C++ 跨越到 Template C++,inheritance(继承)会停止工作。ITPUB个人空间+t#u"n
{y_*]3S+w
ITPUB个人空间]|ov;t
为了重新启动它,我们必须以某种方式使 C++ 的 "don't look in templatized base classes"(不在模板基类中寻找)行为失效。有三种方法可以做到这一点。首先,你可以在调用 base class functions(基类函数)的前面加上 "this->":
C.N)H#mcuv:e8N0ITPUB个人空间} E kU
N}'Z/p!~
template /I"gz
t,_M8|V0class LoggingMsgSender: public MsgSender{ 5\_:QLl;o*IYJ%s5U
N0public: ^nR F _:t#c7D0...ITPUB个人空间|1G/V9\X!vG ITPUB个人空间H9v9R`q3^p:w W void sendClearMsg(const MsgInfo& info)ITPUB个人空间8S`:rq(n9Kig {ITPUB个人空间B8vHT*\u4O1ln write "before sending" info to the log;ITPUB个人空间z[D+l2O4j6D e+wX this->sendClear(info); // okay, assumes thatITPUB个人空间#mE(Q|6F // sendClear will be inherited wJ%JY,U ^3K cN0 write "after sending" info to the log; ,G7dx(m0S*G.WW0} 5v9r6{txD!N0...ITPUB个人空间
~6{6k4|G)m }; |
导入论坛
引用链接
收藏
分享给好友
推荐到圈子
管理
举报
TAG: