Inheritance of CPP templates class templates

Source: Internet
Author: User
Class template inheritance

Class templates can be inherited or inherited.

1. In a class template, a non-dependent base class indicates that the type can be completely determined without knowing the real parameters of the template.
Base class.

For example:

Template <typename x>
Class base {
Public:
Int basefield;
Typedef int T;
};

Class D1: public base <void >{// actually not a template
Public:
Void F () {basefield = 3 ;}
};

Template <typename T>
Class D2: public base <double> {
Public:
Void F () {basefield = 7;} // normal access to inherited members
T strange; // T is base <double >:: T, not a template parameter
};

Note: For non-dependent types in the template, if you find an unrestricted name in its derived class,
Then the non-dependent base class will be searched first before the template parameter list will be searched.

2. Non-dependent names are not found in the dependent base class.

Template <typename x>
Class base {
Public:
Int basefield;
Typedef int T;
};

Template <typename T>
Class DD: Base <t> {
Public:
Void F (){
Basefield = 0; // Problem
}

};

Template <>
Class base <bool> {
Public:
Enum {basefield = 42}; // tricky
};

Void g (DD <bool> & D ){
D. F (); // OPPs
}

// Modify solution 1
Template <typename T>
Class DD1: Base <t> {
Public:
Void F (){
This-> basefield = 0; // the query is delayed.
}

};

// Solution 2
Template <typename T>
Class dd2: Base <t> {
Public:
Void F (){
Base <t>: basefield = 0; // the query is delayed.
}

};

If solution 2 is used to modify the dependency, if the original non-restricted and non-dependent names are used for virtual function calls,
If dependency restrictions are introduced, therefore, the restriction on the introduced dependency will be near the virtual function call.
This will also change the meaning of the Program , solution 1 can be used when the second situation is not suitable.

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.