C++11常用特性介绍——auto类型修饰符

1、C++11常用特性介绍

  从本篇开始介绍C++11常用特性,大致分:关键字及新语法、STL容器、多线程、智能指针内存管理,最后讲一下std::bind和std::function

 

 二、关键字和新语法

1)auto类型修饰符,可以根据初始化代码的内容自动判断变量的类型,而不是显式的指定,如:

  auto a = 1;

  auto b = 'A';

  由于1的类型是int,所以a的类型就是int;同样由于'A'的类型是char,所以b的类型是char。

  如果只是将auto用在变量声明,那将是毫无意义的,auto主要用在遍历。如:

  a)遍历字符串

  std::string str = "hello world";

  for(auto ch : str)

  {

    std::cout << ch << std::endl;

  }

  b)遍历数组

  int array[] = {1,2,3,4,5,6,7,8,9};

  for(auto i : array)

  {

    std::cout << i << std::endl;

  }

  c)遍历vector容器

  std::vector<int> vect = {1,2,3,4,5,6,7,8,9};

  for(auto i : vect)

  {

    std::cout << i << std::endl;

  }

  d)遍历map容器

  std::map<int,int> map = {{1,1}, {2,2}, {3,3}};

  for(auto iter : map)

  {

    std::cout << iter.first << iter.second << std::endl;

  }

  auto的使用为遍历提供了很大的便利,再也不用写那么长的for循环。

  e)定义依赖模板参数的变量类型的模板函数

  template <typename _T1,typename _T2>

  void Addition(_T1 t1,_T2 t2)

  {

    auto v = t1 + t2;

    std::cout << v << std::endl;

  }

  f)定义函数返回值依赖模板参数的变量类型的模板函数

  template <typename _T1,typename _T2>

  auto Addition(_T1 t1,_T2 t2)->decltype(t1 * t2)

  {

    return t1 * t2;

  }

2)注意事项

  a)auto变量必须在定义时初始化,类似于const关键字。

  b)定义一个auto序列的变量必须始终推导成同一类型,如:

    auto a=1,b=2,c=3;  //正确

    auto a=1,b=1.1,c='c';   //错误

  c)如果初始化表达式是引用,则去除引用语义,如:

    int a     = 1;

    int &b   = a;

    auto c  = b;  //c的类型为int而非int&(去除引用)

    auto &d= b;  //d的类型为int&

    c = 100;    //a = 1;

    d = 100;    //a = 100;

  d)如果初始化表达式为const或volatile(或者两者兼有),则除去const/volatile语义,如:

    const int a = 1;

    auto b = a;    //b的类型为int而非const int(去除const)

    auto &c = a;  //c的类型为const int

    const auto d = a;//d的类型为const int

    b = 100;    //合法

    c = 100;    //非法

    d = 100;    //非法

  e)初始化表达式为数组时,auto关键字推导类型为指针

    int a[] = {1,2,3,4,5};

    auto b = a;

    std::cout  <<  typeid(b).name() << std::endl;//输出int[5];

  f)不能作为一些以类型为操作数的操作符的操作数,如sizeof或者typeid:

    std::cout << sizeof(auto) << std::endl;    //错误

    std::cout << typeid(auto).name() << std::endl; //错误

  g)函数参数或者模板参数不能被声明为auto,如:

    template <auto T>

    void Addition(auto a,T t)

    {

    }

posted on 2019-11-13 18:34  zhangnianyong  阅读(865)  评论(0编辑  收藏  举报