C++11:类型推断

auto&decltype

C++98:
auto int a = 10;//自动变量(相对于static, register,extern,可以省略)
                //新标准废弃这种用法
C++11:
int a = 10;
auto 仅仅是一个占位符,并不是一个真正的类型。根据初始化的值推断变量的类型

auto的作用

1.代替较长的声明

std::vector<std::string>strary;
for(std::vector<std::string>::iterator it = strary.begin();it!=strary.end();it++)
{}

for(auto it = strary.begin();it!=strary.end();it++){}

2.模板函数记录结果或者优化计算

template<typename _Tx, typename _Ty>
void Add(_Tx x, _Ty y)
{
    auto res = x+y;
    std::cout<<res;
}

优化计算:

​#define MAX(a,b)({\
    auto _a = (a);\
    auto _b = (b);\
    (_a > _b)? _a : _b;
})

auto注意事项

auto变量必须在定义时初始化:
auto a;//err
auto a  = 10;
auto x {1};
auto z = new auto(1);

定义一个auto序列变量推导成同一类型:
auto a1 = 10,a2='A',a3=3.14;//err;
auto a1= 10,a2 = 20,a3 = 30;//Ok

如果初始化表达式是引用,则去除引用:
int a = 15;
int &b = a;
auto c = b//c为int 而不是int&(去除引用)
auto&d=b; d 为 int&
c = 20; a不变
d = 20; a 变为20

初始化表达式为const或volatile(或both),则去除const/volatile:
const int a = 10;
auto b = a;//b 为非const int (去除const)
const  auto c = a;//c 为const int
b = 20;//ok
c = 20;//err
auto带上&号,不去除const:
const int a = 10;
auto &b = a;//auto 带上&, 所以不去除const,b为const int
b = 10; //err

初始化表达式为数组时,auto关键字推导类型为指针:
int a[3] = {0,1,2};
auto b = a;
auto c[3] = a;//err
cout<<typeid(b).name() <<endl;

若数组且auto带上&,则推导类型为数组类型:
int a[3] = {0,1,2};
auto& b = a;
cout<<typeid(b).name() <<endl;

函数或者模板参数不能被声明为auto:
void func(auto x);//err

非静态成员
struct stu{
        auto val = 10;//err 非静态成员
}
模板参数不可以
vector<auto>v={2};//err

decltype

在定义变量的时候,有时希望从表达式中推断出要定义变量的类型,但又不想用表达式的值去初始化变量(auto)。还有可能是函数返回类型为某表达式的值类型,这时候auto就不能用了,C++11又引入了decltype,作用是选择并返回操作数的数据类型,在此过程中,编译器只是分析表达式并得到它的类型,不计算表达式的值

  1. 单个标记表达式以及访问类成员,推导为本类型
  2. 将亡值,推导为类型的右值引用
  3. 左值推导为左值引用
  4. 以上都不是,推导为本类型

auto结合decltype返回值占位

template<typename _Tx, typename _Ty>
auto Add(_Tx x, _Ty y)->decltype(x+y)
{
    return x+y
}

const int x =2 ,&b = a;
decltype(a) x = 0;//x类型为const int
auto z = a;//z类型为int
decltype(b)y = x; //y类型为 const int&
auto z = b; //  z类型为int

int i = 2;
decltype(i) int类型
decltype((i)) int& 类型

int i = 21;
decltype(i = 54)x = i; // 赋值语句 decltype(i = 54)不运行 返回的是int& x 是i 的引用

int arr[20] = {};
decltype(arr)b; //b 20个元素数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

#A#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值