auto、decltype

auto、decltype

auto

  1. auto关键字不是C++11才引入的之前就有,C++11标准将auto关键字实现为自动类型推断
  2. auto关键字其实就是让编译器通过初始值来推断变量的类型,因此auto定义的变量必须有初始值(必须进行显式初始化)
int x = 10;
auto y = x;   //y的类型为int
auto z;  //未初始化,无法推断
static auto w;  //隐式初始化,无法推断
  1. auto的用法:
    (1)基本用法:
auto x = 10;   //x为int类型
int y = 10;
double w = 20.5;
auto z = y + w;  //y + w为double类型所以z为double类型

(2)auto与引用

int x = 10, *ptr = &x;
auto y = x;   //y为int类型
auto & z = x;  //z为x的引用
auto ptr1 = ptr;  //ptr1为int * 类型
auto * ptr2 = ptr;  //ptr2也为int * 类型

(3)auto与const

const int x = 10;
auto y = x;  //y仍然为int类型而不是const int
const auto y = x;  //此时y才为const int 类型

(4)auto与函数变量

double func(int);
auto func1 = func;  //func1为double(*)(int)类型
  1. auto一般用于类型名比较冗长或者不明确的情况
vector<int> nums{1, 2, 3, 4, 5};
for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)
//替换为
for(auto iter = nums.begin(); iter != nums.end(), iter++)

decltype

1.C++11引入关键字decltype将变量的类型声明为表达式指定的类型,其实就是从表达式中推断出要声明的变量的值
2. 与auto关键字不同,利用decltype定义变量可以不进行初始化
3. decltype的用法:
(1)基本用法:

int x = 10;
decltype(x) y;  //y和x的类型相同仍然是int类型

(2)decltype与const

const int x = 10;
decltype(x) y = 20;
y = 30;   //错误的,y的类型为const int 

(3)decltype与引用

const int x = 10;
const int &y = x;
decltype(y) z = x;  //z为const int&类型
decltype((x)) w = x;
  1. 若表达式类型不是引用类型,但我们需要推断出引用类型,可以在表达式外添加一对括号,就变成了引用类型

(4)decltype与指针

int x = 10, y = 20;
int * ptr = &x;
decltype(ptr) ptr2 = &y;  //ptr2为int * 类型,指向y
decltype(*ptr) z = y;  //z为int &类型,引用y
  1. 对指针的解引用返回的是引用类型

(5)decltype与函数

int show() {return 10;}
decltype(show())  y = 20;  //y的类型为int类型
  1. 编译器只是通过分析表达式或函数然后得到他的类型,并不会真实去执行函数或计算表达式的值
  1. decltype主要用于模板的定义,以为只有等到实例化后才能知道确定类型:
    在这里插入图片描述

返回值后置

  1. 返回值后置是C++11新增的一种函数声明的语法,返回值的类型放在参数列表后面
  2. 返回值后置一般用于无法确定返回值类型的场景下,一般也是在模板中使用
  3. 返回值后置通常要借助auto关键字和decltype关键字完成
double func(int x);   //原始函数声明的方法
auto func(int x)->double
template <typename T, typename U>
auto func(T &, U &) -> decltype(T*U)
{
	return T*U;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

m0_46427273

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

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

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

打赏作者

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

抵扣说明:

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

余额充值