zoukankan      html  css  js  c++  java
  • 读书笔记 effective c++ Item 43 了解如何访问模板化基类中的名字

    1. 问题的引入——派生类不会发现模板基类中的名字

    假设我们需要写一个应用,使用它可以为不同的公司发送消息。消息可以以加密或者明文(未加密)的方式被发送。如果在编译阶段我们有足够的信息来确定哪个信息会被发送到哪个公司,我们可以使用基于模板的解决方案:

     1 class CompanyA {
     2 public:
     3 ...
     4 void sendCleartext(const std::string& msg);
     5 void sendEncrypted(const std::string& msg);
     6 ...
     7 };
     8 class CompanyB {
     9 public:
    10 ...
    11 void sendCleartext(const std::string& msg);
    12 void sendEncrypted(const std::string& msg);
    13 ...
    14 };
    15 
    16 ...                                                       // classes for other companies
    17 
    18 class MsgInfo { ... };                            // class for holding information
    19 // used to create a message
    20 
    21 template<typename Company>
    22 class MsgSender {
    23 public:
    24 ...                                                       // ctors, dtor, etc.
    25 
    26 void sendClear(const MsgInfo& info)
    27 {
    28 std::string msg;
    29 create msg from info;
    30 Company c;
    31 c.sendCleartext(msg);
    32 }
    33 void sendSecret(const MsgInfo& info)           // similar to sendClear, except
    34 
    35  
    36 
    37 { ... }                                              // calls c.sendEncrypted
    38 
    39 }        

                                           

     这会工作的很好,但是假设有时候我们需要在发送信息之前log一些信息。一个派生类就能够很容易的添加这些信息,下面的实现看上去是合理的实现方式:

     1 template<typename Company>
     2 
     3 class LoggingMsgSender: public MsgSender<Company> {
     4 
     5 public:
     6 
     7  
     8 
     9 ...                                                         // ctors, dtor, etc.
    10 
    11 void sendClearMsg(const MsgInfo& info)     
    12 
    13 {                                                         
    14 
    15 write "before sending" info to the log;
    16 
    17 
    18 sendClear(info); // call base class function;
    19 // this code will not compile!
    20 write "after sending" info to the log;
    21 }
    22 ...
    23 };

    注意派生类中的消息发送函数和基类相比(sendClear)是一个不同的名字(sendClearMsg)。这是好的设计,因为这避免了隐藏继承而来的名字的问题(Item 33),同时避免了重新定义继承而来的非虚函数问题Item 36)。但是代码不能通过编译,至少符合标准的编译器不能通过编译。这些编译器会发出sendClear不存在的抱怨。我们能够看到sendClear是在基类中,但是编译器没有在基类中发现它。我们需要知道为什么。

    2. 问题分析

    2.1 一般化分析

    问题出现在当编译器遇到类模版LoggingMsgSender的定义时,它们不知道它继承自什么类。当然,它是继承自MsgSender<Company>,但是Company是一个模板参数,这个参数只有在LoggingMsgSender被实例化的时候才会被确认。在不知道Company是什么的情况下,我们也不知道MsgSender<Company>是什么样子的。因此也就没有方法获知是否存在sendClear函数。

    2.2 用实例来证明问题所在

    为了使问题更加具体,假设我们有一个类CompanyZ使用加密的方式进行通信:

     1 class CompanyZ {                                               // this class offers no
     2 
     3 public:                                                                // sendCleartext function
     4 
     5 ...                                                                       
     6 
     7 void sendEncrypted(const std::string& msg);   
     8 
     9 ...                                                                       
    10 
    11 };

    普通的MsgSender模板对于CompanyZ来说是不合适的,因为普通模板提供了一个对于CompanyZ对象来说没有意义的函数。为了改正这个问题,我们能够为CompanyZ创建一个MsgSender的特化版本:

    1 template<>                                     // a total specialization of
    2 
    3 class MsgSender<CompanyZ> {      // MsgSender; the same as the
    4 
    5 
    6 public: // general template, except
    7 ... // sendClear is omitted
    8 void sendSecret(const MsgInfo& info)
    9 { ... }

    注意在类定义开始的地方出现的”template<>” 语法。它表明这既不是模板也不是单独的类。它是当使用CompanyZ作为模板参数时,会使用到的MsgSender模板的特化版本。这叫做模板全特化(total template specialization):模板MsgSender为类型CompanyZ进行了特化,并且特化是全特化——一旦类型参数被定义为ComanyZ,模板参数的其它地方就不会再发生变化

    在MsgSender已经有了CompanyZ的特化版本的情况下,再看一下派生类LoggingMsgSender:

     1 template<typename Company>
     2 class LoggingMsgSender: public MsgSender<Company> {
     3 public:
     4 ...
     5 void sendClearMsg(const MsgInfo& info)
     6 {
     7 write "before sending" info to the log;
     8 sendClear(info); // if Company == CompanyZ,
     9 // this function doesn’t exist!
    10 write "after sending" info to the log;
    11 }
    12 ...
    13 };

    正如注释中所写的,当基类是MsgSender<CompanyZ>的情况下这段代码没有意义,因为基类中没有提供sendClear函数。这也是C++拒绝这个调用的原因:它认识到基类模板可能被特化了,但是特化版本并没有提供普通模板中的一般接口。因此,它拒绝在模板化基类中寻找继承而来的名字。从某种意义上讲,当我们从面向对象C++转到模板C++的时候(Item 1),继承就会停止工作。

    3. 如何解决问题——三种方法

    如果让其重新工作,我们必须让C++“不在模板化基类中寻找“的行为失效。有三种方法达到这个目标。

    第一,调用基类函数时你可以为其加上”this->“

     1 template<typename Company>
     2 class LoggingMsgSender: public MsgSender<Company> {
     3 public:
     4 ...
     5 void sendClearMsg(const MsgInfo& info)
     6 {
     7 write "before sending" info to the log;
     8 this->sendClear(info); // okay, assumes that
     9 // sendClear will be inherited
    10 write "after sending" info to the log;
    11 }
    12 ...
    13 };

    第二,你可以使用using声明,你可能会熟悉,因为Item 33中用了类似的解决方案。那个条款中解释了如何使用using声明来将隐藏起来的基类名字带入派生类作用域。我们于是可以像下面这种方式实现sendClearMsg:

     1 template<typename Company>
     2 class LoggingMsgSender: public MsgSender<Company> {
     3 public:
     4 using MsgSender<Company>::sendClear; // tell compilers to assume
     5 ... // that sendClear is in the
     6 // base class
     7 void sendClearMsg(const MsgInfo& info)
     8 {
     9 ...
    10 
    11 sendClear(info);                                  // okay, assumes that
    12 
    13 ...                                                          // sendClear will be inherited
    14 
    15 }                                                         
    16 
    17 ...                                                        
    18 
    19 };             

                                             

    最后,让你的代码通过编译的方法是在基类中明确指出需要调用的函数

     1 template<typename Company>
     2 
     3 class LoggingMsgSender: public MsgSender<Company> {
     4 
     5 public:
     6 
     7 ...
     8 
     9 void sendClearMsg(const MsgInfo& info)
    10 
    11 {
    12 
    13 ...
    14 
    15 MsgSender<Company>::sendClear(info);
    16 
    17 // okay, assumes that
    18 
    19 
    20 ... // sendClear will be
    21 } // inherited
    22 ...
    23 };

    这基本上会是你最不愿意使用的解决这个问题的方法,因为如果被调用的函数是virtual的,显示的限定符会关掉virtual绑定行为。

    从名字可见性的观点来看,每个方法都做了同样的事情:它向编译器许诺,接下来的任何基类模板特化都会支持一般模板提供的接口。这样的许诺是当所有的编译器解析一个像LoggingMsgSender的派生类模板的时候所需要的,但是如果这个许诺并没有兑现,在接下来的编译中真理就会浮现。例如,如果下面的源码有这种情况:

    1 LoggingMsgSender<CompanyZ> zMsgSender;
    2 MsgInfo msgData;
    3 ...                                                                  // put info in msgData
    4 
    5 zMsgSender.sendClearMsg(msgData);         // error! won’t compile

    对sendClearMsg的编译不会通过,因为从这个点上来说,编译器知道基类是模板的特化版本MsgSender<CompanyZ>,并且它们知道这个类没有提供sendClearMsg想要调用的sendClear函数。

    4. 本条款讨论的根本所在

    从根本上来说,这个问题是编译器对基类成员的无效引用进行诊断的早(当派生类模板被解析的时候)或晚(当这些模板用特定的模板参数进行实例化的时候)的问题。C++的方针是更加喜欢早点诊断,这也是为什么当类从模板中特化的时候,它假定对基类的内容一无所知。

    5. 总结

    在派生类模板中,引用基类模板中的名字可以使用“->this“前缀,通过使用using声明,或者通过使用显示的使用基类限定符。

  • 相关阅读:
    SharePoint 2010 User Profile Sync Service自动停止
    如何区别多个svchost.exe?
    Log Parser分析IIS log的一个简单例子
    Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
    Windows中右键点击文件夹, 结果找不到共享选项卡, 怎么办?
    介绍SOS中的SaveModule命令
    SharePoint中Draft版本的文档不会收到document added的Alert Email
    和我一起学Windows Workflow Foundation(1)创建和调试一个WF实例
    门户网站
    C#基础—— check、lock、using语句归纳
  • 原文地址:https://www.cnblogs.com/harlanc/p/6665825.html
Copyright © 2011-2022 走看看