C + + 11 Common features Description: AUTO,DECLTYPE,NULLPTR,FOR,LAMBDA

Source: Internet
Author: User

What is c++11

C++11, formerly known as C++0X, is an extension and correction of the current C + + language, c++11 not only contains the new functions of the core language, but also expands the standard library of C + + (STL), incorporating most of the C + + Technical report 1 (TR1) Library (except for special math functions).

C++11 includes a number of new features: a lambda expression, a type deduction keyword auto, a decltype, and a lot of improvements to the template.

This article will give a brief explanation of the above new features of c++11, so that you can quickly understand the great role of c++11 in the ease of use of C + +.

If you feel that the layout of this article is not very comfortable, you can view my PDF document: Baidu Plate link

New Keyword Auto

The first function of introducing auto in C++11 is for automatic type deduction

Automatic type deduction for auto, used to infer the data type of a variable from an initialization expression. Automatic type deduction from auto can greatly simplify our programming work

Auto actually compiles the variables at compile time, so it does not adversely affect the efficiency of the program's operation.

In addition, it seems that auto does not affect the compilation speed, because the compile time will also be the right derivation and then determine whether to match the left.

auto a; // 错误,auto是通过初始化表达式进行类型推导,如果没有初始化表达式,就无法确定a的类型auto i = 1;auto d = 1.0;auto str = "Hello World";auto ch = ‘A‘;auto func = less<int>();vector<int> iv;auto ite = iv.begin();auto p = new foo() // 对自定义类型进行类型推导

Auto not only has the above application, it is also a skill in the template, such as the following example of this process product example, if you do not use AUTO, you must declare the product template parameters:

template <typename Product, typename Creator>void processProduct(const Creator& creator) {    Product* val = creator.makeObject();    // do somthing with val}       

If you use auto, you can write this:

template <typename Creator>void processProduct(const Creator& creator) {    auto val = creator.makeObject();    // do somthing with val}

Discarding the problematic template parameters, the entire code becomes more positive.

Decltype

Decltype is actually a bit like auto's inverse function, Auto lets you declare a variable, and decltype can get the type from a variable or an expression, with the following example:

int x = 3;decltype(x) y = x;

Some people will ask, where is the utility of Decltype, and we continue with the above example, if we want to use the product as the return value in the example of the processed product above? We can write this:

template <typename Creator>auto processProduct(const Creator& creator) -> decltype(creator.makeObject()) {    auto val = creator.makeObject();    // do somthing with val}
Nullptr

Nullptr is a new type introduced to solve the two semantic problem of NULL in the original C + + because NULL actually represents 0.

void F(int a){    cout<<a<<endl;}void F(int *p){    assert(p != NULL);        cout<< p <<endl;}int main(){        int *p = nullptr;    int *q = NULL;    bool equal = ( p == q ); // equal的值为true,说明p和q都是空指针    int a = nullptr; // 编译失败,nullptr不能转型为int    F(0); // 在C++98中编译失败,有二义性;在C++11中调用F(int)    F(nullptr);    return 0;}
Sequence for loop

In C + +, A For loop can use a simplified for loop like Java, which can be used to iterate over arrays, containers, strings, and sequences defined by the Begin and end functions (that is, with iterator), as shown in the example code:

#include <iostream>#include <map>using namespace std;int main(){    map<string, int> m{{"a", 1}, {"b", 2}, {"c", 3}};    for (auto p : m) {        cout << p.first << ":" << p.second << endl;    }    return 0;}
#g++ -o m2  -std=c++11  m2.cc
Lambda expression

Lambda expressions are similar to closures in JavaScript, which can be used to create and define anonymous function objects to simplify the programming effort. The syntax for Lambda is as follows:

[function Object parameter] (operator overloaded function parameter), return value type {function Body}

vector<int> iv{5, 4, 3, 2, 1};int a = 2, b = 1;for_each(iv.begin(), iv.end(), [b](int &x){cout<<(x + b)<<endl;}); // (1)for_each(iv.begin(), iv.end(), [=](int &x){x *= (a + b);});     // (2)for_each(iv.begin(), iv.end(), [=](int &x)->int{return x * (a + b);});// (3)

The parameters within [] refer to the global variables that a lambda expression can take. (1) B in the function means that the function can get global variables outside the lambda expression, and if it is passed in [], then all external variables, such as (2) and (3) lambda expressions, can be obtained.
The parameters in () are the arguments passed in each time the function is called.
Plus is the type of the lambda expression return value, such as a variable of type int returned in (3)

Template for variable length parameters

We've used Pair,pair in C + + to construct a container that contains two different types of data using the Make_pair construct. For example, the following code:

auto p = make_pair(1, "C++ 11");

Since the variable-length parameter template was introduced in c++11, a new data type was invented: Tuple,tuple is an n-tuple that can pass in 1, 2 or more different types of data

auto t1 = make_tuple(1, 2.0, "C++ 11");auto t2 = make_tuple(1, 2.0, "C++ 11", {1, 0, 2});

This avoids the ugly practice of nesting pair in the previous pair, making the code cleaner

Another frequently seen example is the print function, where printf can pass in multiple parameters in C, and in c++11, we can use the variable-length parameter template to achieve a more concise print

template<typename head, typename... tail>void Print(Head head, typename... tail) {    cout<< head <<endl;    Print(tail...);}

Several different kinds of parameters can be passed in print, as follows:

Print(1, 1.0, "C++11");
A more elegant initialization method

Before introducing c++11, only arrays can use the initialization list, and other containers want to use the initialization list, only in the following ways:

int arr[3] = {1, 2, 3}vector<int> v(arr, arr + 3);

In c++11, we can use the following syntax to replace:

int arr[3]{1, 2, 3};vector<int> iv{1, 2, 3};map<int, string>{{1, "a"}, {2, "b"}};string str{"Hello World"};
Reference

If you want to learn more about the exciting new features of c++11, I would recommend these two blogs to you:

Towrting's C++11 Series blog: http://towriting.com/blog/2013/08/01/what-is-cpp11/

Compiler support list for c++11: http://cpprocks.com/c11-compiler-support-shootout-visual-studio-gcc-clang-intel/

C + + 11 Common features Description: AUTO,DECLTYPE,NULLPTR,FOR,LAMBDA

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.