Templates in C + +

Source: Internet
Author: User

1. Generic Programming

--the implementation of a common standard container library. The so-called Universal Standard Container Library, is to do: for example, the list class to store all the Ken type of objects such things; generic programming lets you write a fully generalized and reusable algorithm that is as efficient as the algorithm designed for a particular data type. Generics are meant to be manipulated on a variety of data types, similar to templates.

--Representative works of generic programming STL is an efficient, generic, interoperable software component.


2, how to write a general addition??

1 uses a function overload to re-implement it for each of the different types of the same behavior that you want.

Cons: 1 If a new type appears, add the corresponding function again.

2 "In addition to the type, all functions of the function body are the same, the code reuse rate is not high."

3 "function overloading does not solve the problem if the function simply returns a value of type different.

4 "A method has a problem, all the methods have problems, not good maintenance.

2 uses a common base class to place common code inside a common base class.

Cons: 1 by using a common base class to write generic code, you lose the benefits of type checking.

2 "For many of the classes that are implemented later, they must inherit from a particular base class, and code maintenance is more difficult.

3 uses a special preprocessing program.

Cons: 1 not a function, no parameter type check, security is not high.

4 You can also use generic programming.


3. Generic Programming:

1. Writing a type-independent logic code is a means of code reuse. Templates are the basis for generic programming.

2 "Template: function template, class template


4. Function Template:

1 The function template represents a family of functions, which are parameterized when used, producing a specific type of function based on the argument type.

2 The format of the function template:

Note: 1>typename is used to define template parameter keywords, or you can use class (recommended to use TypeName as much as possible)

2> but cannot use struct

3 "Function templates can also be defined as inline functions. (but inline must be placed after the template parameter table, before the return value, cannot be placed before the stencil)


4 "Template is a blueprint, itself is not a class or function, compiler with a template to produce a particular class or function of a specific type version, the process of producing a template-specific type is called a function template instantiation.


5, the actual argument deduction:

The process of determining template parameter types and values from function arguments is called template argument deduction. Arguments for multiple type parameters must match exactly.


6. Type parameter conversion:

1 generally does not convert arguments to match an existing instantiation, but instead produces a new instance.

2 The compiler performs only two conversions:

1>const conversion: A function that receives a const reference or a const pointer can be called by a reference or a pointer to a non-const object, respectively

2> array or function-to-pointer conversions: If the template parameter is not a reference type, the arguments to the arrays or function types should be converted with regular pointers. An array real arguments as a pointer to its first element, and a function argument as a pointer to a function type.


7. Template parameters:

1 The function template has two types of parameters: template parameters and call parameters.

2 "and the template parameters are divided into: type parameter and non-type form parameter

3 "template parameter names can only be used after template parameters to the end of a template declaration or definition, following the name masking rule.

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

5 "All template parameters must be preceded by a class or typename keyword modifier.

6 Note You cannot specify a default template argument inside a function template.


8. Non-template type parameters:

A non-template type parameter is a constant defined inside a template, and a non-template type argument can be used when a constant expression is required.


9. Template parameter Description:

1 "Template formal parameter list is used <>.

2, like the function parameter table, must be separated by commas with multiple arguments, and the type can be the same or different.

3 "template parameter list cannot be empty.

4 The template parameter can be a type parameter, or it can be a non-type parameter. The type parameters follow the class and TypeName.

5 "template type parameter can be used as a type description trailing characters anywhere in the template, in exactly the same way as a built-in type or custom type, to specify function parameter types, return values, local variables, and coercion type conversions.

6 "Template parameter table, class and TypeName have the same meaning, can be exchanged with each other, using typename more intuitive. But the keyword TypeName is added to C + + as a C + + standard, and the compiler may not support it.


+ +, template function overloading:

Note: Both the function and all overloaded versions of the declaration should be bit-domain before the function is called at the location.

Description

1 "A non-template function can exist with a function template of the same name, and the function template can be instantiated as this non-template function.

2 for non-template functions and function templates with the same name, if all other conditions are the same, the non-template function will be called first instead of an instantiation from the template. If a template can produce a function that has a better match, the template is selected.

3 displays an empty template argument list that tells the compiler that only Muangthong can match this call. And all the templates should be interpreted according to the actual parameters.

4 "The template function does not allow automatic type conversions, but ordinary functions can perform automatic type conversions.


10, the function template of the Special:

The template functions are in the following form:

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

2 "then the template name and a pair of angle brackets, in angle brackets specify the template parameter for this special definition.

3 "function formal parameter list

4 "Function body

Note: This function template must already exist before the special, and the same number of parameters.

template <typename T>bool isequal (t left, t right) {return left = = right;} Template<>bool isequal<const char*> (const char * pleft, const char * pright)//<const char*> here is equivalent to replacing t {return pleft = = Pright;}     11, template Parameters--adapter: stack (using template implementation stack--LIFO) template <typename t>class seqlist{private:int _size;     int _capacity; t* _data;};/ /template <class T, template<class> class container>template <class T, template<class> class Contai     NER = seqlist>//default parameter class Stack{public:void Push (const t& x);     void Pop ();     Const t& TOP (); BOOL Empty ();p rivate:container<t > _con;};     void Test () {stack<int> S1; Stack<int, seqlist> S2;} 
Template parameters-Implementation Queue Template<typename t,template< TypeName T > class containter>//And then nested a template type parameter, the keyword here must be class-- --Only the class template parameter can specify a default value class Queue{public:                Queue ()                {}                 void pushback (const t& D)                {                                _con. Pushback ();                }                 void Popfront ()                {                                _con. Popfront ();                } Private:                 containter<t > _con;}; int main () {                 queue<int,seqlist> q;                Q.pushback (1);                Q.pushback (2);                Q.popfront ();                 return 0;}


12. Non-type template parameters:

Static order table//template<typename T, size_t max_size>template <typename t, size_t max_size = 10>//with default template parameters class SeqL Ist{public:     seqlist ();p rivate:     T _array [max_size];     int _size;}; Template <typename T, size_t max_size>seqlist <t, Max_size>::seqlist ()    : _size (0) {}void Test () {     seqlist<int> S1;     Seqlist<int, 20> S2;}



13. Template class:

The template class is also a template and must be preceded by a keyword template followed by a templated parameter list.


14, the template class instantiation:

1 "As long as there is a different type, the compiler will instantiate a corresponding class.

2 "seqlist<int>SL1 seqlist<Double>SL2;When defining these two types of sequential tables, the compileruse int and double instead of template parameters, rewrite the Seqlist class, and finally create a class named Seqlist<int> and Seqlist<double>.


15, the class template of the Special: two kinds of--local special, full of special

Note: Defining member functions after full customization eliminates the need for template parameters

1 "Type extraction

2 "Pod type extraction


16. Separation and compilation of templates:

--Solution:

1 "Add template class Seqlist<int After the definition of template classes, which is shown in templates header file Xxx.h >; This method is generally not recommended, on the one hand, the old compiler may not support, on the other hand instantiation of the dependent callers. (Not recommended)

2. Put the Declaration and definition into a file "xxx.hpp", it is recommended to use this method .


17. Template Summary:

--Advantages:

1 "Template reuse code, save resources, faster iterative development, C + + Standard Template Library (STL) resulting.

2 increases the flexibility of the code.

--Disadvantages:

1 template makes code messy, difficult to maintain, and time-coded to grow.

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


Templates in C + +

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.