正 文

C++箴言:如何访问模板化基类中的名字


www.7dspace.com  更新日期:2005-12-10 2:40:51  七度空间


  问题在于当编译器遇到 class template(类模板)LoggingMsgSender 的 definition(定义)时,它们不知道它从哪个 class(类)继承。当然,它是 MsgSender<Company>,但是 Company 是一个 template parameter(模板参数),这个直到更迟一些才能被确定(当 LoggingMsgSender 被实例化的时候)。不知道 Company 是什么,就没有办法知道 class(类)MsgSender<Company> 是什么样子的。特别是,没有办法知道它是否有一个 sendClear function(函数)。

  为了使问题具体化,假设我们有一个要求加密通讯的 class(类)CompanyZ:

class CompanyZ { // this class offers no
 public: // sendCleartext function
 ...
 void sendEncrypted(const std::string& msg);
 ...
};

  一般的 MsgSender template(模板)不适用于 CompanyZ,因为那个模板提供一个 sendClear function(函数)对于 CompanyZ objects(对象)没有意义。为了纠正这个问题,我们可以创建一个 MsgSender 针对 CompanyZ 的特化版本:

template<> // a total specialization of
class MsgSender<CompanyZ> { // MsgSender; the same as the
public: // general template, except
... // sendCleartext is omitted
void sendSecret(const MsgInfo& info)
{ ... }
};

  注意这个 class definition(类定义)开始处的 "template <>" 语法。它表示这既不是一个 template(模板),也不是一个 standalone class(独立类)。正确的说法是,它是一个用于 template argument(模板参数)为 CompanyZ 时的 MsgSender template(模板)的 specialized version(特化版本)。这以 total template specialization(完全模板特化)闻名:template(模板)MsgSender 针对类型 CompanyZ 被特化,而且这个 specialization(特化)是 total(完全)的——只要 type parameter(类型参数)被定义成了 CompanyZ,就没有剩下能被改变的其它 template's parameters(模板参数)。

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

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

3页,页码:[1] [2] [3] 

上一篇:照片处理:优化MM照片的眉毛、睫毛和眼睛
下一篇:用VC实现多串口多线程工业控制
作者:fatalerror99  来源:blog ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐