Effective modern C + + reading note Item 1

Source: Internet
Author: User
Tags volatile

Recently discovered "effective modern C + +" This book, the author is the famous Scott meyers--"effective C + +", "effective STL" author.

And in the c++11 gradually popularized, even c++14 new features into everyone's vision, "effective modern C + +" a book emerged. The book, like its predecessors, was launched through dozens of articles, only this time focusing on new features of C++11 and c++14. Auto,decltype, move, lambda expression ... What are the details and essentials behind these powerful new features? ......

Reading this book, I feel the joy of the enlightened and the beginner C + + when looking at Scott's previous writings indistinguishable. Then try to extract one or two, combined with the thought, do some records, but also try to check some of their own knowledge points have what shortcomings, I hope you can correct me.

Attention:

Clam Clam Clam

↑ ↑ ↑ A fragment of such a box does not come from the original book at all , It's my own understanding.

Item 1 Understand template type deduction

The title of Item 1 is presumably translated into "Understanding template type Deduction". Template type deduction is a long-term feature of C + +. Like what:

template<typename t>void  f (paramtype param); f (expr);   // F

Where Paramtype can be a type related to T , but contains some adornments, such as a const or reference modifier (reference qualifier). Such as:

Template<typename t>void F (const//    const T &

For such a call:

int 0 ; F (x);

A Specialize function is generated by a type derivation,T is deduced (deduce) is int, andparamtype is deduced as a const int & .

The above process is type deduction, and

void f<int> (int);

It is not a type derivation-because it is not a "type deduction", but rather a direct designation of--cppreference called Instantiate, instantiated. The compiler will specialized function templates with specific template parameters.

In this form, the derivation ofT depends not only on the type of expr , but also on the form of paramtype (form). Three scenarios are given in this book:

Scenario 1: paramtype is a pointer (pointer) or reference (reference) type, but not a universal reference (Universal Reference)

(The book does not detail what is called a universal reference, but it does not have much effect because the universal reference is not an lvalue reference first, that is, it is not a shape such as int&, t&)

In the first case, the type derivation has the following rules:

    1. If the expr type is a reference, omit the reference part;
    2. After this, the type of expr is matched to Paramtype to determine T.

In two,expr refers to the function's argument (argument), and paramtype is the type of the formal parameter (parameter). Examples in the book are:

  template<typename t>void  F (t&  param);  int  x = 27   const  int  cx = X;  const    int  & Rx = x;f (x);  //  T-int, paramtype-int&
      f (CX); //   f (RX); //   

expr, which is the x, CX, RXof the previous example, int,const intAfter removing the reference part, and param is going to establish a reference to these types of variables, Paramtype The above results are deduced.

One of the most important:

When passing a const object to a reference parameter (parameter), the caller expects the object to maintain the const attribute, which is invariant.

Template type deduction follows this point. Therefore, passing the Const object to the template parameter t& is safe and does not lose the const attribute.

And the above rules are also valid for rvalue references.

When the paramtype In the example above is changed to Const t& , the above three calls will be paramtype deduced as const int& amp;T is intevery time. Since the paramtype has a constin its form, the T does not need to have a const after matching.

The derivation process is the same for the case where the paramtype is a pointer. Just remove the "ignore references" step and just pattern match the pointer type.

Scenario 2: Paramtypeis a universal reference

The parameters of the template function are universal references, such as the "Like" rvalue (rvalue) reference, which is the t&& type, where T is the template type parameter.

I think, the so-called universal reference, you can refer to the "Reference overlay effect" table first:

& & &
& && &
&& & &
&& && &&

I think this may be done:& referenced by & Reference is & Reference,& reference && reference is & Reference,&& Reference & Reference is & reference ...

My understanding is that any of the referenced && references are prototypes, so they are called universal references. Because it is superimposed on an indeterminate template type T, the notation is the same, but it is not an rvalue reference because the Rvalue reference works on the explicit type.

Reference http://stackoverflow.com/questions/20364297/why-universal-references-have-the-same-syntax-as-rvalue-references

For universal references, the type inference rule is:

    1. If expr is an lvalue (Lvalue), then both T and paramtype are deduced as lvalue references;
    2. If expr is an rvalue (rvalue), then the "normal" rule-the rule of the first case-is applied.

Rule 1 can be referenced to the overlay table, the type ofexpr is the right side, if it is the left value is &, can be universal by the reference to such a state is also only left &. Even if paramtype is declared to be a similar form to rvalue references,Paramtype itself is deduced as an lvalue reference.

I think this derivation is precisely because the pending Paramtype cannot represent an rvalue reference type, but can only be used as a type op-expression with an unknown quantity T. For example, if T is int&&, then t& is int&.

Examples of Case 2 in the book are:

Template<typename t>voidF (t&& param);//param is now a universal reference
intx = -;Const intCX = x;Const int& rx = x;
f (x);//x-Lvalue, T-Int&Paramtype-int&F (CX);//CX-and Lvalue, T-and const int&paramtype, const int&F (RX);//RX--Lvalue, T-and const int&paramtype, const int&F -);//rvalue, T-int,Paramtype-int&&

The 4th invocation is the case of the return Case 1 rule. expr is an rvalue that is bound to int&&after a pattern match, where T is an int.

Scenario 3: paramtype Not a pointer, not a reference

Just like this, pass by value/by copy (Pass-by-value):

Template<typename t>void f (T param);

Then param always copies the arguments (argument). There are rules for this situation:

    1. expr The type is a reference, ignoring the reference part;
    2. after const , ignoring const . If it is still volatile , this is also ignored.
  int  x = 27 ; const  int  cx = x; const  int  & rx = x;   
f (x); // T and paramtypes, int f (CX); // T and paramtypes, int f (RX); // T and paramtypes, int

Because param is always a copy of expr , no matter how expr is affected, expr 's the properties of const andvolatile are irrelevant to param .

This is also in line with the above, where the caller expects an object to be passed in with an attribute (such as const) that is not affected, and the implementation of the program should follow this hope.

The original book here is an example of a const char * Const passed by copy (passed by value-relative to by reference), not a small table.

Array as an argument

There is one such feature in C + + that is the degradation of arrays (decay):

 Constchar"hello";  // Const CHAR[6] Const char *p = str;         // array degenerate to pointer

It is obvious that the types of str and p are different. And for the syntax in C, you can declare the parameters of a function as an array, but the following are the same:

void func (char  str[]); void func (char *str);

This is because the array form of the formal parameter (parameter) is treated as a parameter in the form of a pointer.

Therefore, for the template parameter T passed by value, when the argument is an array of char[] ,t is deduced as char *. (You can assume that the degradation of an array occurs first.) )

But when the template parameter is a reference, it is able to "really" refer to the incoming array (that is, no array degradation occurs):

Template<typename t>void f (t& param); f (str);    // Const CHAR[6], Paramtype, const char (&) [6]

An example of getting the array size from the template at compile time (the temporarily irrelevant part of the code is removed):

Template<typename T, std::size_t n>constexpr std::size_t arraySize (t (&    return  N;}

function as an argument

In addition to the array, the function is returned as a pointer. But at the same time, the template can be used to provide reference type parameters to avoid degradation:

void somefunc (intdouble//  somefunc  , void (int, double)
Template<typename t>void F1 (T param);

Template<typename t>void f2 (t& param);
// Paramtype Void (*) (int, double) // Void (&) (int, double)

The degradation of arrays and functions is for their identifiers.

Note Points for this article
    1. In type deduction, an argument of a reference type is considered non-referenced.
    2. For the type deduction of formal parameters in universal reference form, the Lvalue argument requires special handling.
    3. Arguments passed by value are ignored for both const and volatile .
    4. In type inference, when an identifier for an array or function is used, if it is not used to initialize the reference, it causes it to degenerate into a pointer.

Effective modern C + + reading note Item 1

Related Article

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.