Jeff's seventh day of learning C + +: template (end!!!)

Keywords: C++

1, What is a template

Template is C++Automatic code generation technology in.

2, Why use templates

Problem: implement a general sorting algorithm.
    C Language: it is realized through callback function, which is troublesome for users to call.
    C++Language: function overloading requires the implementation of a first version for multiple types, which will also lead to the increase of code segments.
    C/C++Language: with the help of macro functions, the type check is not strict, and frequent use will add code segments.
For the above reasons C++The father of C++Template technology is implemented in, which can not only have many kinds of technologies, but also give consideration to strict type checking, and enable programmers to focus on business logic rather than relational data types.

3, Function template

1. Definition of function template

template <typename T1,typename T2,...>
T2 function name (T1, A1, T2, A2)
{
T1 v1;
T2 v2 = x;
return v2;
}

You can use any identifier as a type parameter, but use T It's a conventional agreement.
typedef You can also change it to class There is no difference between them.

2. Use of function templates
The C + + compiler does not compile the function template into an entity that can handle all types, but produces different function entities according to the parameters provided by the caller.

The process of bringing in function templates according to specific types to generate function entities is called instantiation.

The template is materialized only when it is called:
    Auto instantiation: automatically determine the type according to the data type provided by the caller.
    Manual instantiation: func<type,...>(parameter)
        The type parameter of the template, which is used when it is not related to the parameter of the function.

The parameter type of the template can also use the default parameter.

3. Instantiation process of template function
The first template function will undergo secondary compilation. The first compilation is to check whether the template code itself is correct before instantiation. The second compilation is to bring the type parameters provided by the caller into the template and check the template code again during instantiation.

The second compilation generates binary function instructions. The first compilation only generates a data structure used to describe the template in the compiler's memory.

4. Restrictions on automatic instantiation of template functions
1. Function parameters are not related to template parameters.
2. The return value type cannot be inferred implicitly.

5. Specialization of template
Templates are not suitable for all situations, so you can implement a normal function for a special type.
Before instantiation, the template function will check whether there is a normal version of the function. If there is, it will not be instantiated again. Therefore, the template function will not conflict with the normal function.

4, Class template

1. Definition format of class template

template <typename M,typename R,typename A,typename O>
class Test
{
private:
M val;
public:
R func(A a)
{
O a;
}
};

2. Use of class templates
The type parameter of the template class cannot be implicitly broken, that is, it cannot be instantiated automatically. The type parameter must be explicitly specified.
Class name < type > object;

The use of class templates is divided into three steps:
    1,Check the syntax of the class template, and if so, generate a class data structure in the compiler.
    2,Replace the type parameters provided by the user into the class template and check the syntax again. If it is legal, the compiler will instantiate the class template and generate the creation instruction of the class object.
    3,Execute the creation instruction of class object to create class object.
    Note: the member functions of a class are not all instantiated, but are instantiated by the caller(Generate binary instructions). 

3. Static member of class template
The members in the class should be declared in the class, defined outside the class (except those with const attribute), and the static members of the class template are the same.

template <typename T>
class Test
{
    static int val1;
    static T val2; 
public:
};
template<typename T>int Test<T>::val1 = value;
template<typename T>T Test<T>:: val2 = value;

4. Recursive instantiation
The parameters of the template can be of any type, as long as the class provides the functions required in the template code.
Class template is already a type after instantiation, so it can only be used as a parameter of the template. This instantiation is called recursive instantiation.

5. Local specialization of class templates
When the member function of a class cannot be generalized, it is necessary to implement a special version of the member function for a special type, which is called local specialization of the class and must be implemented outside the class.
Template < > return value type class name < special type >:: function name (parameter list)
{

}

6. Global specialization of class templates
To implement a special version of a class for a particular type is called global specialization of the class.
Template < > class class name < special type >
{
...
};

7. Default parameters for class templates
The default parameters can also be set for the parameters of the class template. The usage is the same as that of the function template (right).

5, STL

STL yes Stand Template Library Abbreviations, also known as the standard template library, are provided by HP Labs.

It is divided into the following contents:
    Container: some common data structures that can store any data type.
    Algorithm: some common algorithms, such as search, sorting, comparison, exchange and copy.
    Iterator: a tool that helps you use containers in a way similar to pointers.

1. Iterator
Class objects that implement * and - > operators, and also support + + / – operators, can easily traverse, access and operate containers.
Forward iterator: container type < type >: iterator it;
Using the + + operator is equivalent to traversing the container from beginning to end.
The begin member function of the container can get the starting value of the forward iterator.
The end member function of the container can get the end of the forward iterator (after the last element).
Normally normal iterator: container type < type >:: const_ iterator cit;
The const attribute added on the basis of the forward iterator can no longer modify the value of the container element through the iterator.
Reverse iterator: container type < type >: reverse_ iterator rit;
Using the + + operator is equivalent to traversing the container backwards from end to end.
Constant inverse iterator: container type < type >:: const_ reverse_ iterator crit;
const attribute added on the basis of inverse iterator.

2. Container:
Vector
Supported operators: = =,! =, < =, > =, <, > []
Constructor:
vector();
vector( size_type num, const TYPE &val );
vector( const vector &from );
vector( input_iterator start, input_iterator end );

    void assign( input_iterator start, input_iterator end );
    Will interval[start, end)Assign the element to the current vector

    void assign( size_type num, const TYPE &val );
    Fu num Values are val Element to vector in

    TYPE at( size_type loc );
    amount to[]Function, at() Function ratio [] Operators are safer, Because it won't let you visit Vector Elements that are out of bounds, when out of bounds at Will throw exceptions, and[]Dirty data, segment errors, etc. may occur.

    iterator erase( iterator loc );
    If you delete an element, the previous iterator has been damaged. You need to receive its return value again.

    iterator erase( iterator start, iterator end );
    Delete a batch of elements

    size_type size();
    Gets the number of current elements
stack,queue,deque,priority_queue
    Iterators cannot be used.
    deque It is called double ended queue. Both ports can enter and exit.
    priority_queue The priority queue will be sorted automatically according to the value of the element. The order out of the queue is the order after sorting. It needs to be implemented when storing custom type objects < Operator.
set
    Collection container is characterized by that elements cannot be repeated and will be sorted automatically. It does not support operators and only has no parameter construction. It needs to be implemented when storing custom type objects < Operator.        
    pair equal_range( const key_type &key );
    Returns two iterators in the collection that are equal to the upper and lower bounds of the given value.

    iterator lower_bound( const key_type &key );
    Returns a point greater than or equal to key Iterator for the first element of the value.

    iterator upper_bound( const key_type &key );
    Returns a pointer greater than in the current collection Key Iterator for the element of the value.
multiset
    Multiple collection containers, and set The difference is that elements can be repeated.
map
    It is called a mapping container. In other programming languages, it is also called a dictionary. Its elements are composed of key/value Consists of key value pairs.
    pair<key Type, value type>(k,v) Create a key pair.
    
    iterator insert( iterator pos, const pair<KEY_TYPE,VALUE_TYPE> &val );
    void insert( input_iterator start, input_iterator end );
    pair<iterator, bool> insert( const pair<KEY_TYPE,VALUE_TYPE> &val );
    After inserting elements, they are sorted automatically, key Type to support<Operator.

    iterator find( const KEY_TYPE &key );
    Its query efficiency is very high, and the red black tree is used for storage at the bottom.
    
    pair Type access data:
        first
        second
multimap:
    The difference from mapping lies in its key It can be repeated and returned during query key Iterator for all elements that are equal.
    
bitset It can convert an unsigned long integer into binary, which is convenient for position operation.

Posted by tonchily on Mon, 20 Sep 2021 19:57:47 -0700