auto 与decltype 两种类型推断

auto与decltype区别主要有三个方面:

  1. auto类型计算后推断,decltype不进行计算;
  2. auto会忽略掉顶层const,保留下层const;decltype全部进行保留;
  3. 与auto不同,decltype结果类型与表达式形式密切相关;加上括号与不加括号不同。
#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{
    int a = 3;
    auto c1 = a;
    decltype(a) c2 = a;
    decltype((a)) c3 = a;

    const int d = 5;
    auto f1 = d;
    decltype(d) f2 = d;

    cout << typeid(c1).name() << endl;
    cout << typeid(c2).name() << endl;
    cout << typeid(c3).name() << endl;
    cout << typeid(f1).name() << endl;
    cout << typeid(f2).name() << endl;

    c1 ++;
    c2 ++;
    c3 ++;
    f1 ++;
    //f2 ++;

    cout << a << " " << c1 << ' ' << c2 << " " << c3 << ' ' << f1 << ' ' << f2 << endl;


}

auto的推断策略

推断的精髓在右值,根据右值的形式,简单的简单推断和复合推断。
引用指向指针的时候,要注意隐藏的const 输定,需要用const auto进行声明

例如下面代码

int i=100;
cosnt auto ci=23;//right
auto ci=23;//wrong

auto &test_i=i;//正确,test_i 是int 型,因为i是int型
const auto &p=&i;//right,变量定义后,马上为其分配存储,变量名i与地址&i进行了束定,绑死在一起,是一种隐含的const关系。
auto &q=&i;//wrong,
auto &x=p;//right


完整测试代码

#include <iostream>
#include <typeinfo>

using namespace std;

int main()
{
    int i=1,&ri=i;
    const int ci=21,&rci=ci;

    //以下全部为int
    auto a=1;
    auto b=i;
    auto c=ri;
    auto d=ci;
    auto e=rci;

    auto f=&i;//整型指针
    auto g=&ci;//指向常量的指针,下层的const不可忽略

    //以下是复合类型(引用)
    //auto &ra=1;//错误
    auto &rb=i;rb++;
    auto &rc=ri;rc++;
    auto &rd=ci;//整型常量, const int 类型
    auto &re=rci;//整型常量, const int 类型


    //auto &k=21;

    const auto &k=21;
    const auto ck=ci;
    const auto cki=i;

    //一样的
    auto *p=&ci;
    auto q=&ci;
    cout<<typeid(p).name()<<' '<<q<<endl;
    cout<<typeid(q).name()<<' '<<p<<endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值