C ++ proverbs: how to access the names of templated base classes

Source: Internet
Author: User
C ++ tips: how to access the name of the templated base class-general Linux technology-Linux programming and kernel information. The following is a detailed description. Suppose we want to write an application that can send messages to several different companies. Messages can be transmitted in either encrypted or plaintext (not encrypted) mode. If we have enough information to determine which message will be sent to which company during compilation, we can use a template-based solution to solve the problem:

Class CompanyA {
Public:
...
Void sendCleartext (const std: string & msg );
Void sendEncrypted (const std: string & msg );
...
};

Class CompanyB {
Public:
...
Void sendCleartext (const std: string & msg );
Void sendEncrypted (const std: string & msg );
...
};
... // Classes for other companies

Class MsgInfo {...}; // class for holding information
// Used to create a message
Template
Class MsgSender {
Public:
... // Ctors, dtor, etc.

Void sendClear (const MsgInfo & info)
{
Std: string msg;
Create msg from info;

Company c;
C. sendCleartext (msg );
}
Void sendSecret (const MsgInfo & info) // similar to sendClear, counter t
{...} // Callc. sendEncrypted
};

This works well, but suppose we sometimes need to record some information into the log every time a message is sent. Using a derived class (derived class), you can simply add this function. The following seems a reasonable method:

Template
Class LoggingMsgSender: public MsgSender {
Public:
... // Ctors, dtor, etc.
Void sendClearMsg (const MsgInfo & info)
{
Write "before sending" info to the log;
SendClear (info); // call base class function;
// This code will not compile!
Write "after sending" info to the log;
}
...
};


Note that the name (sendClearMsg) of the message-sending function (message sending function) in the derived class (derived class) corresponds to the one (where, it is called sendClear. This is a good design because it avoids the problem of hiding inherited names (hiding inherited names) (See C ++ proverbs: avoiding overwriting the names obtained through inheritance). and redefine the inherent problems of an inherited non-virtual function (inherited non-virtual function) (See C ++ proverbs: do not redefine the inherited non-virtual functions.) However, the above Code cannot be compiled, at least in a compliant compiler. Such a compiler will complain that sendClear does not exist. We can see that sendClear is in the base class (base class), but the compiler won't look for it there. We need to understand why.

The problem is that when the compiler encounters the class template (class template) LoggingMsgSender's definition (definition), they do not know which class it inherits from. Of course, it is MsgSender, but Company is a template parameter (template parameter), which can only be determined later (when LoggingMsgSender is instantiated ). Without knowing what Company is, there is no way to know what class (class) MsgSender looks like. In particular, there is no way to know whether it has a sendClear function (function ).

To make the problem more specific, suppose we have a class (class) CompanyZ that requires encrypted communication:
Class CompanyZ {// this class offers no
Public: // sendCleartext function
...
Void sendEncrypted (const std: string & msg );
...
};

Generally, MsgSender template (template) is not applicable to CompanyZ, because the template provides a sendClear function (function) that is meaningless to CompanyZ objects (object. To solve this problem, we can create a special version of MsgSender for CompanyZ:

Template <> // a total specialization
Class MsgSender {// MsgSender; the same as
Public: // general template, role t
... // SendCleartext is omitted
Void sendSecret (const MsgInfo & info)
{...}
};

Note the "template <>" syntax at the beginning of this class definition (class definition. It indicates that this is neither a template nor standalone class ). The correct statement is that it is a specialized version (special version) used for the MsgSender template (template parameter) when the template argument (template parameter) is CompanyZ ). This is famous for its total template specialization (full template specialization): template (template) MsgSender is specially tailored to the CompanyZ type, and this specialization (specialization) is total (complete) -- as long as the type parameter (type parameter) is defined as CompanyZ, there will be no other template's parameters (template parameter) that can be changed ).

MsgSender is known to be specially crafted for CompanyZ. Next, consider derived class (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;
}
...
};

As written in comments, when the base class (base class) is MsgSender, the code here is meaningless because the class does not provide the sendClear function (function ). This is why C ++ rejects this call: it recognizes that the base class templates (base class template) can be made special, and this feature is not necessarily provided with the general template (general template) the same interface ). As a result, it usually rejects the search for inherited names (inherited names) in the templatized base classes (templated base class ). In a sense, when we span from Object-oriented C ++ to Template C ++, inheritance will stop working.

To restart it, we must invalidate the "don't look in templatized base classes" (not found in the template base class) of C ++ in some way. There are three ways to do this. First, you can add "this->" before calling base class functions (base class function ":

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;
}
...
};

Second, you can use a using declaration. If you have read C ++ proverbs: Avoid overwriting the names obtained through inheritance, this should be a solution you are familiar. This article explains how using declarations can introduce hidden base class names (base class name) into a derived class (derived class) field. Therefore, we can write sendClearMsg as follows:

Template
Class LoggingMsgSender: public MsgSender {
Public:
Using MsgSender: sendClear; // tell compilers to assume
... // That sendClear is in
// Base class
Void sendClearMsg (const MsgInfo & info)
{
...
SendClear (info); // okay, assumes that
... // SendClear will be inherited
}
...
};

(Although using declaration works in both of the following languages: Do not overwrite the names obtained through inheritance, the problems to be solved are different. In this case, the base class names (the base class name) is not hidden by the derived class names (the name of the derived class), but the compiler will not search for the base class field if we do not tell it to do so .)

The last way to compile your code is to explicitly specify that the called function is in the base class (base class:

Template
Class LoggingMsgSender: public MsgSender {
Public:
...
Void sendClearMsg (const MsgInfo & info)
{
...
MsgSender: sendClear (info); // okay, assumes that
... // SendClear will be
} // Inherited

...
};

This is usually the most undesirable method to solve this problem, because if the called function is virtual, the virtual binding will be disabled explicitly.

From the perspective of name visibility, every method has done the same thing: it guarantees the compiler the specializations (special) of any subsequent base class template (base class template) interfaces provided by general templates are supported ). All compilers are parsing a derived class template (derived class template) Like LoggingMsgSender. Such a guarantee is necessary, but if it is confirmed that it is not true, the truth will be exposed during subsequent compilation. For example, if the following source code contains,

LoggingMsgSender zMsgSender;
MsgInfo msgData;
... // Put info in msgData
ZMsgSender. sendClearMsg (msgData); // error! Won't compile

Calls to sendClearMsg cannot be compiled, because at this moment, the compiler knows that base class (base class) is template specialization (template-specific) MsgSender, and they also know that class (class) no sendClear function (function) is provided ).

Basically, the problem is that the compiler diagnoses illegal reference to base class members (base class members) earlier (when the derived class template definitions (derived class template definition) is parsed, later (when templates (templates) are instantiated by specific template arguments (template parameters. C ++'s policy is to prefer early diagnosis, and that's why when those classes (classes) are instantiated from templates (templates), it pretends not to know base classes (base classes).

Things to Remember

· In derived class templates (derived class template), you can reference the name in base class templates (base class template) through the "this->" prefix, via using declarations, or through an explicit basic class qualification ).
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.