Summary of objective Modern C ++ Item 2, inclutivemodernc

Source: Internet
Author: User

Summary of objective Modern C ++ Item 2, inclutivemodernc
First, we propose two basic points of view:

1. auto and template parameter type derivation have almost identical rules, so the rules summarized in Item1 are applicable to auto.

2. There is a difference between auto and template parameter type derivation. The difference is that the process for curly braces is different. Why is it different? Rule! Scotter Meyer does not know the answer.

 

We know Item1 and propose three different cases:

1. The type descriptor is a pointer or reference, and is not a global reference.

2. the type descriptor is a global reference.

3. the type descriptor is neither a pointer nor a reference

template<typename T> void f(ParamType param);

 



In short, we can regard auto as T in the parameter descriptor of the template function.

const int x=5;auto y=x;    //y is int.auto yy= 5; //yy is int.const auto cy = yy;

 

The above code type derivation follows case3, and all auto types are int.

const auto& ry= yy;

 

The above Code follows case1.

auto&& uref1 = x; // x is int and lvalue, // so uref1's type is int&auto&& uref2 = cx; // cx is const int and lvalue, // so uref2's type is const int&auto&& uref3 = 27; // 27 is int and rvalue, // so uref3's type is int&&

 

Case2.

 

Let's talk about the difference.

Auto converts curly brackets to the initialization list.

auto x3 = { 27 }; // type is std::initializer_list<int>, // value is { 27 }

 

Using the template as follows is incorrect.

template<typename T> // template with parametervoid f(T param); // declaration equivalent to // x's declarationf({ 11, 23, 9 }); // error! can't deduce type for T

 

 

In addition, for C ++ 14, the compiler cannot infer the type returned by curly braces, including functions and lambda.

The auto parameter type of lamda cannot be inferred.

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.