01 C++11 auto与decltype

声明:以上文章是基于对微信公众号“程序喵大人”文章学习,原文地址链接,欢迎大家关注支持原作者!

C++11引入了auto和decltype关键字,使用他们可以在编译期就推导出变量或者表达式的类型。

auto

auto可以通过=右边的类型推导出变量的类型;

auto a = 10; // 10是int型,可以自动推导出a是int
int i = 10;
auto b = i; // b是int型
auto d = 2.0; // d是double型

auto的推导规则与限制

先说结论,下面的为详细说明代码:
1. auto的使用必须马上初始化,否则无法推导出类型
2. auto在一行定义多个变量时,各个变量的推导不能产生二义性,否则编译失败
3. auto不能用作函数参数
4. 在类中auto不能用作非静态成员变量
5. auto不能定义数组,可以定义指针
6. auto无法推导出模板参数
7. 在不声明为引用或者指针时,atuo会忽略等号右边的引用类型和const/volatile限定
8. 在声明为引用或者指针时,atuo会保留等号右边的引用类型和const/volatile限定

int i = 10;
auto a = i, &b = i, *c = &i; // a是int,b是i的引用,c是i的指针,auto就相当于int
auto d = 0, f = 1.0; // error,0和1.0类型不同,对于编译器有二义性,没法推导
auto e; // error,使用auto必须马上初始化,否则无法推导类型


void func(auto value) {} // error,auto不能用作函数参数

class A {
    auto a = 1; // error,在类中auto不能用作非静态成员变量
    static auto b = 1; // error,这里与auto无关,正常static int b = 1也不可以
    static const auto int c = 1; // ok
};

void func2() {
    int a[10] = {0};
    auto b = a; // ok
    auto c[10] = a; // error,auto不能定义数组,可以定义指针
    vector<int> d;
    vector<auto> f = d; // error,auto无法推导出模板参数
}

auto关于指针、引用、const讨论

int i = 0;
auto *a = &i; // a是int*
auto &b = i; // b是int&
auto c = b; // c是int,忽略了引用

const auto d = i; // d是const int
auto e = d; // e是int

const auto& f = e; // f是const int&
auto &g = f; // g是const int&

decltype

decltype则用于推导表达式类型,这里只用于编译器分析表达式的类型,表达式实际不会进行运算

int func() { return 0; }
decltype(func()) i; // i为int类型

int x = 0;
decltype(x) y; // y是int类型
decltype(x + y) z; // z是int类型

decltype推导规则

对于decltype(exp)有
1. exp是表达式,decltype(exp)和exp类型相同
2. exp是函数调用,decltype(exp)和函数返回值类型相同
3. 其它情况,若exp是左值,decltype(exp)是exp类型的左值引用


int a = 0, b = 0;
decltype(a + b) c = 0; // c是int,因为(a+b)返回一个右值
decltype(a += b) d = c;// d是int&,因为(a+=b)返回一个左值

d = 20;
cout << "c " << c << endl; // 输出c 20

4. decltype不会像auto一样忽略引用和cv属性,decltype会保留表达式的引用和cv属性

cont int &i = 1;
int a = 2;
decltype(i) b = 2; // b是const int&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值