Templates in C ++

Source: Internet
Author: User

Templates in C ++

1. Generic programming

-- Implements a general standard container library. The so-called general standard container library is to do this: for example, the List class stores all the kenun-type objects. Generic programming allows you to compile a completely general and reusable algorithm, the efficiency is the same as the algorithm designed for a specific data type. Generic refers to being able to operate on multiple data types, which is similar to the template.

-- STL, a representative of generic programming, is an efficient, generic, and interactive software component.

 

2. How to compile a general addition ??

1. Use Function overload to re-implement it for different types of the same behavior required.

Disadvantages: 1, as long as there is a new type, it is necessary to re-Add the corresponding function.

2. Except for types, all functions share the same body, and the code reuse rate is not high.

3. Function overloading cannot solve the problem if the function only has different return value types.

4. There is a problem with a method. All methods have problems and are difficult to maintain.

2. Use the public base class to place the common code in the public base class.

Disadvantages: 1. Using the public base class to write common code will lose the advantage of type check.

2. Many classes implemented in the future must inherit from a specific base class, making code maintenance more difficult.

3. Use special preprocessing programs.

Disadvantages: 1 "is not a function. Parameter type check is not performed and the security is not high.

4. You can also use generic programming.

 

3. Generic programming:

1. Writing logic code irrelevant to types is a means of code reuse. Templates are the basis of generic programming.

2. templates are divided into function templates and class templates.

 

4. Function template:

1. The function template represents a function family, which is parameterized during use and generates a specific type of function based on the real parameter type.

2. Function template format:

Note: 1> typename is used to define template parameter keywords. You can also use class (we recommend that you use typename whenever possible)

2> but cannot use struct

3. function templates can also be defined as inline functions. (However, inline must be placed after the template parameter table, before the return value, not before the template)

 

4. A template is a blueprint. It is not a class or function. The compiler uses a template to generate a specific version of a specific class or function. The process of generating a specific type of template is called function template instantiation.

 

5. Real parameter deduction:

The process of determining the type and value of the template parameters from the function parameters is called the real parameter deduction of the template. The real parameters of multiple types must be completely matched.

 

6. Type parameter conversion:

1. In general, real parameters are not converted to match the existing instantiation. On the contrary, new instances are generated.

2. the compiler only performs two conversions:

1> const conversion: functions that receive const references or const pointers can call non-const object references or pointers respectively.

2> array or function-to-pointer conversion: If the template parameter is not of the reference type, regular pointer conversion should be used for the real parameters of the array or function type. Array arguments are treated as pointers to their first element, and function arguments are used as pointers to function types.

 

7. template parameters:

1. function templates have two types of parameters: template parameters and call parameters.

2, and template parameters are classified into: type parameters and non-type parameters

3. The template parameter name can only be used between the template parameter name and the end of the template declaration or definition. The name blocking rule is followed.

4. The name of the template parameter can only be used once in the same template parameter list.

5. class or typename keywords must be added before all template parameters.

6. Note that the default real parameters of the template cannot be specified within the function template.

 

8. Non-template parameters:

A non-template type parameter is a constant defined in the template. When a constant expression is required, you can use a non-template type parameter.

 

9. template parameters:

1. Use the template parameter table <>.

2 "is the same as the function parameter table. Multiple parameters must be separated by commas (,). The type can be the same or different.

3. The template parameter table cannot be blank.

4. The template parameters can be type parameters or non-type parameters. The type parameter follows class and typename.

5. template type parameters can be used anywhere in the template as type specifiers. They are used exactly the same as built-in or custom types, it can be used to specify the function parameter type, return value, local variable, and forced type conversion.

6. In the template parameter table, class and typename have the same meaning and can be exchanged with each other. Using typename is more intuitive. However, if the keyword typename is added to C ++ as the C ++ standard, the compiler may not support it.

 

9 +. template function overloading:

Note: the Declaration of the function and all overloaded versions should be prior to the called position of the function.

Note:

1. A non-template function can coexist with a function template with the same name, and the function template can be instantiated as a non-template function.

2. For non-template functions and function templates with the same name, if other conditions are the same, the non-template functions will be called preferentially, instead of generating an instantiation from the template. If the template can generate a function with better matching, the template will be selected.

3. A list of specified empty template arguments is displayed. This syntax tells the compiler that only you can match this call with Mamba. All templates should be interpreted based on real parameters.

4. template functions do not allow automatic type conversion, but normal functions can perform automatic type conversion.

 

10. Function template features:

The form of template function specialization is as follows:

1. Keyword template followed by an empty pair of angle brackets <>

2 "is followed by the Template Name and a pair of angle brackets. The angle brackets specify the template parameters of this special definition.

3. function parameter table

4. Function body

Note: The function template must already exist and have the same number of parameters.

Template
 
  
Bool IsEqual (T left, T right) {return left = right;} template <> bool IsEqual
  
   
(Const char * pleft, const char * pright) //
   
    
It is equivalent to replacing T {return pleft = pright;} 11. template parameter -- adapter: stack (use template to implement stack -- post-in-first-out) template
    
     
Class SeqList {private: int _ size; int _ capacity; T * _ data;}; // template
     
      
Class Container> template
      
        Class Container = SeqList> // default parameter class Stack {public: void Push (const T & x); void Pop (); const T & Top (); bool Empty (); private: Container
       
         _ Con ;}; void Test () {Stack
        
          S1; Stack
         
           S2 ;}
         
        
       
      
     
    
   
  
 
Template parameters -- Implement queue template
 
  
Class Containter> // nest another template type parameter. The keyword here must be class ---- only class template parameters can specify the default value class Queue {public: Queue () {} void PushBack (const T & d) {_ con. pushBack ();} void PopFront () {_ con. popFront ();} private: Containter
  
   
_ Con ;}; int main () {Queue
   
    
Q; q. PushBack (1); q. PushBack (2); q. PopFront (); return 0 ;}
   
  
 

 

12. Non-type template parameters:

// Static sequence table // template
 
  
Template
  
   
// Class SeqList {public: SeqList (); private: T _ array [MAX_SIZE]; int _ size ;}; template
   
    
SeqList
    
     
: SeqList (): _ size (0) {} void Test () {SeqList
     
      
S1; SeqList
      
        S2 ;}
      
     
    
   
  
 


 

13. template class:

The template class is also a template. It must begin with the keyword template and be followed by the template form parameter table.

 

14. template class instantiation:

1. As long as there is a different type, the compiler will take a corresponding class as an example.

2 SeqList Sl1 SeqList Sl2; when defining the above two types of sequence tables, the compiler will use int and double to replace the template parameters, re-compile the SeqList class, and finally create the SeqList class And SeqList .

 

15. Special templates: there are two types: localized and fully-specific

Note: After the feature is fully customized, the member function is defined and the template parameters are no longer required.

1 "type Extraction

2 POD Extraction

 

16. Separate template compilation:

-- Solution:

1. display the instantiation in the template header file xxx. h-> Add templateclassSeqList after the Template Class Definition This method is generally not recommended. On the one hand, the old compiler may not support this method, and on the other hand, it instantiates dependent callers. (Not recommended)

2. Place the Declaration and definition in a file "xxx. hpp". This method is recommended.

 

17. template summary:

-- Advantages:

1. Templates reuse code, saving resources, and faster iterative development. This is why C ++'s standard template library (STL) is generated.

2. Enhanced code flexibility.

-- Disadvantages:

1. The template makes the code messy and complex, difficult to maintain, and the compilation time becomes longer.

2. When a template compilation error occurs, the error information is very messy and difficult to locate the error.

 

 

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.