C ++ template practice 4: Template Specialization

Source: Internet
Author: User

The purpose of the template design is to be universal, but in some cases there are also special situations that are independent of general rules. Therefore, the template needs to be customized in special circumstances.

For a class 1 template, enter the name of the specific type after the template class name <>. <> This part is called the matching type, as shown below:

Template
 
  
// General template void show (); template <> // The template parameters of the special template. The parameter is no longer required, so it is null. <> void show cannot be omitted.
  
   
(); // Special template, where
   
    
Called matching
   
  
 
The special rules are as follows:

1) The matching formula is written after the Template Class Name and wrapped with <>, even if the template is not added with a new type parameter, <> cannot be omitted

2) List of Projects separated by commas in the matching formula, as shown in the previous And the number of projects must be the same as the number of common template parameters, that is, the general template parameters here are T, N, so the special time cannot be similar to the show

3) in the matching formula, each project type must be consistent with the common template parameter type.

4) A matching project can be a specific template parameter value or a specific type.

5) when a matching project is a type template parameter, it is similar to a function variable, and the template parameters can also be modified using *, &, const, volatile, etc.

Example:

// Template used for template-type template parameters
 
  
Struct S1; // template example. There are three template parameters: type parameter, non-type parameter, and template parameter.
  
   
Class SP> // general template struct S; // Case 1, matching S
   
    
Template
    
     
Class SP> struct S
     
      
; // Case 2, matching S
      <任意有const修饰的类型, 任意整数, s1>
        Template
       
         Class SP> struct S
        
          ; // Special case 3, full special case, only matching S
         
           Template <> // This example is completely special, and the rest are specially crafted struct S
          
            ; // Special case 4, using the template instance as the type parameter value. Matching S
           
             , 10, S1> template
            
              Struct S
             
               , 10, S1>; // exception 5, Error! The number of matched items is inconsistent with the number of example parameters. // template
              
                Class SP, typename TT> // struct S
               
                 ; // Exception 6, Error! The type of the matched project is different from that of the example parameter. // template
                
                  // Struct S
                 
                   ; // Exception 7, Error! The SP type of the template parameter is inconsistent with that of the SP type in the general example. // template
                  
                    Class SP> // struct S
                   
                     ;
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 

Two types of template matching follow the best matching principle. The example is as follows:

# Include
 
  
Template
  
   
Struct S {std: string id () {return "General" ;}}; // exception 1. The third parameter must be chartemplate.
   
    
Struct S
    
     
{Std: string id () {return "Specialization #1" ;}}; // exception 2. Constraints 2 and 3 must be chartemplate
     
      
Struct S
      
        {Std: string id () {return "Specialization #2" ;}}; // Special Case 3: The first parameter must be int, and the second and third parameters are the same as the template.
       
         Struct S
        
          {Std: string id () {return "Specialization #3" ;}}; int main () {using namespace std; cout <S
         
           (). Id () <endl; // General cout <S
          
            (). Id () <endl; // Specialization #3 cout <S
           
             (). Id () <endl; // Specialization #1 cout <S
            
              (). Id () <endl; // Specialization #2 // cout <S
             
               (). Id () <endl; // matching 2, 3, with ambiguity}
             
            
           
          
         
        
       
      
     
    
   
  
 

3. function templates are special and overloaded functions. When function templates are completely special, they are similar to overloaded functions. However, the template instantiation code is expanded by the compiler during compilation, so it is inline. When multiple template instances or common functions of the same type are combined, the function matching rules are as follows:

1) The best matching principle is based on the matching degree of the real parameter and the form parameter.

2) normal functions take precedence over template instances

3) High priority for template instances with high degree of specialization

Example:

# Include
 
  
Using namespace std; template
  
   
Void fun (T x, N y) {cout <"#1" <
   
    
Void fun (T x, int y) {cout <"#2" <
    
     
// The function template does not allow some special features. It can only be fully special. // void fun
     
      
(T x, char y) {// cout <"#3" <
      
        Void fun
       
         (Char x, char y) {// fully specialized cout <"#4" <
        
          Void fun (double x, double y) {cout <"#5" <
         
           (1, 2); // universal template fun
          
            (1, 'A'); // universal template fun <> ('A', 'B'); // specify the special version fun
           
             Fun ('A', 'B'); // common function fun (char x, char y). If this common function is not available, the fully-specialized version fun (3.14, 3.14156); // fully special version fun (true); // normal function fun (bool x) return 0 ;}
           
          
         
        
       
      
     
    
   
  
 
Program output:

#1 1 2#1 1 a#4 a b#7 a b#5 3.14 3.14156#6 1

4. The template is specially used to determine the condition during compilation. The example is as follows:

# Include
 
  
Template
  
   
Void print () {print
   
    
(); Std: cout <I <std: endl;} // special case, terminate recursion. Template <> void print <1> () {std: cout <1 <std: endl;} int main () {print <100> (); // during the compilation period, expansion is equivalent to 100 output statements}
   
  
 
Program output:

1

2

....

100


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.