C++11类型推导


2.1 auto

auto的自动类型推导,用于从初始化表达式中推断出变量的数据类型。从这个意义上讲,auto并非一种“类型”声明,而是一个类型声明时的“占位符”,编译器在编译时期会将auto替换为变量实际的类型。

通过auto的自动类型推导,可以大大简化我们的编程工作:

#include 
#include 
#include <string>
using namespace std;

double foo() {}

void func(vector<string> & tmp)
{
    for (auto i = tmp.begin(); i < tmp.end(); i++)
    {
        // 一些代码
    }
}

int main()
{
    auto x = 1;      // x的类型为int
    auto y = foo();  // y的类型为double
    struct m { int i; }str;
    auto str1 = str;    // str1的类型是struct m

    auto z;     // err, 无法推导,无法通过编译
    z = x;

    return 0;
}

注意点:
void fun(auto x =1) {}  // 1: auto函数参数,有些编译器无法通过编译

struct str
{
    auto var = 10;   // 2: auto非静态成员变量,无法通过编译
};

int main()
{
    char x[3];
    auto y = x;
    auto z[3] = x; // 3: auto数组,无法通过编译

    // 4: auto模板参数(实例化时),无法通过编译
    vector x = {1};

    return 0;
}
#include
#include
#include
usingnamespacestd;
 
doublefoo(){}
 
voidfunc(vector<string>&tmp)
{
    for(autoi=tmp.begin();i<tmp.end();i++)
    {
        //一些代码
    }
}
 
intmain()
{
    autox=1;      //x的类型为int
    autoy=foo();  //y的类型为double
    structm{inti;}str;
    autostr1=str;    //str1的类型是structm
 
    autoz;     //err,无法推导,无法通过编译
    z=x;
 
    return0;
}

 

注意点:

voidfun(autox=1){}  //1:auto函数参数,有些编译器无法通过编译
 
structstr
{
    autovar=10;   //2:auto非静态成员变量,无法通过编译
};
 
intmain()
{
    charx[3];
    autoy=x;
    autoz[3]=x;//3:auto数组,无法通过编译
 
    //4:auto模板参数(实例化时),无法通过编译
    vector<auto>x={1};
 
    return0;
}

2.2 decltype

decltype实际上有点像auto的反函数, auto可以让你声明一个变量,而decltype则可以从一个变量或表达式中得到其类型,如下:

#include 
#include 
#include 
using namespace std;
 
int main()
{
    int i;
    decltype(i) j = 0;
    cout << typeid(j).name() << endl;   // 打印出"i", g++表示integer
 
    float a;
    double b;
    decltype(a + b) c;
    cout << typeid(c).name() << endl;   // 打印出"d", g++表示double
 
    vector<int> vec;
    typedef decltype(vec.begin()) vectype; // decltype(vec.begin()) 改名为 vectype
 
    vectype k;  
    //decltype(vec.begin()) k;  
    for (k = vec.begin(); k < vec.end(); k++)
    {
        // 做一些事情
    }
 
    enum {Ok, Error, Warning}flag;   // 匿名的枚举变量
    decltype(flag) tmp = Ok;
 
    return 0;
}

相关