C++ 11 之推导关键词

时间:2023-03-08 20:39:25

C++ 11新增了两个推导关键词,auto & decltype

1.区别

auto:用于推导变量类型;

decltype: 用于推导表达式或者函数返回值

2.直接上代码

intmain()
{
    conststd::vector<);
    autoa = v[];        // a 的类型是 int
    decltype(v[]) b = ; // b 的类型是 const int&, 因为函数的返回类型是
                          // std::vector<int>::operator[](size_type) const
    autoc = ;           // c 的类型是 int
    autod = c;           // d 的类型是 int
    decltype(c) e;        // e 的类型是 int, 因为 c 的类型是int
    decltype((c)) f = c;  // f 的类型是 int&, 因为 (c) 是左值
    decltype() g;        // g 的类型是 int, 因为 0 是右值
}

3.auto的最主要用处是STL中的迭代子类型,使得代码简介;

 使用前:
     std::map<std::string, std::vector<int>> map;
     std::map<std::string, std::vector<int>>::iterator it;
     for (it = map.begin(); it != map.end(); ++it)
     {
     }

 使用后:
     std::map<std::string, std::vector<int>> map;
     for(auto it = begin(map); it != end(map); ++it)
     {
     }
     

4.扩展

获取auto的类型,使用typeid; 
#include <typeinfo>
auto i = 10;
cout<<typeid(i).name()<<endl;