Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92427645
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-15 21:30:33

    来源:赛迪论坛    作者:sixth

已知 MsgSender 针对 CompanyZ 被特化,再次考虑 derived class(派生类)LoggingMsgSender:

template
class LoggingMsgSender: public MsgSender {
 public:
 ...
 void sendClearMsg(const MsgInfo& info)
 {
  write "before sending" info to the log;
  sendClear(info); // if Company == CompanyZ,
  // this function doesn't exist!
  write "after sending" info to the log;
 }
 ...
};

  就像注释中写的,当 base class(基类)是 MsgSender 时,这里的代码是无意义的,因为那个类没有提供 sendClear function(函数)。这就是为什么 C++ 拒绝这个调用:它认可 base class templates(基类模板)可以被特化,而这个特化不一定提供和 general template(通用模板)相同的 interface(接口)。结果,它通常会拒绝在 templatized base classes(模板化基类)中寻找 inherited names(继承来的名字)。在某种意义上,当我们从 Object-oriented C++ 跨越到 Template C++,inheritance(继承)会停止工作。

  为了重新启动它,我们必须以某种方式使 C++ 的 "don't look in templatized base classes"(不在模板基类中寻找)行为失效。有三种方法可以做到这一点。首先,你可以在调用 base class functions(基类函数)的前面加上 "this->":

template
class LoggingMsgSender: public MsgSender {
public:
...

void sendClearMsg(const MsgInfo& info)
{
 write "before sending" info to the log;
 this->sendClear(info); // okay, assumes that
 // sendClear will be inherited
 write "after sending" info to the log;
}
...
};

阅读(280) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~