C++11特性-自动类型推导

1.推导变量类型-auto

        在c++11中,可以使用auto自动推导变量的类型,也可以结合decltype来表示函数的返回值

        在使用auto时,必须初始化(auto 变量名= 变量值),以便编译器推导实际类型,在编译阶段,将auto占位符替换为真正的类型

int temp = 1435;
auto temp1 = temp;//int
auto &temp2 = temp;//int&
auto temp3 = &temp;//int*
auto *temp4 = &temp;//int*

        当变量为指针或者引用时,推导结果会保留const、volatile关键字,否则不会保留这些关键字

const auto a1 = temp;//const int
auto a2 = a1;//int
const auto &a3 = temp;//const int&
auto &a4 = a3;//const int&
const auto& a3 = temp;//const int&
auto* a5 = &a1;//const int

        不能使用auto的场景:

                1.不能作为函数参数使用

                2.不能用于类的非静态成员变量初始化

                3.不能定义数组

                4.无法推导除模板参数

        推荐使用auto的场景:

                1.遍历STL的容器

                2.用于泛型编程(auto val= 调用模板函数的返回值)

2.推导表达式类型-decltype

        decltype 表达式(不需要初始化),主要用于泛型编程

        推导规则:

                1.当表达式为普通变量、普通表达式、类表达式,推导出来的类型与表达式的类型是一致的

    int x = 99;
	const int& y = x;
	decltype (x)a = x;//int
	decltype (y)b = x;//const int&
	decltype (Test::vasl)c = 10;//static const int
	Test t;
	decltype (t.str)d = "";//string

                2.表达式是函数调用,推导出来的类型是函数的返回值类型

        当函数返回纯右值(字面量常量),对于纯右值,只有类类型可以携带const、volitile限定符能推导出来,除此之外要忽略此限定符

int funcR() {}
int& funcRR() {}//左值引用
int&& funcRRR() {}//右值引用
const int funcC() {}
const int& funcCC() {}
const int&& funcCCC() {}
const Test funcT() {}    

decltype (funcR())aa1;//int
decltype (funcRR())aa2 = x;//int &
decltype (funcRRR())aa3 = 0;//int &&
decltype (funcC())aa4;//int,返回纯右值(字面量)忽略const
decltype (funcCC())aa5 = x;//const int&
decltype (funcCCC())aa6 = 0;//const int&&
decltype (funcT())aa7 = Test();//const Test

        3.表达式是一个左值(可以取地址的变量),或者被()包围,推导出来是表达式的引用,此情况下不能忽略const、volitile限定符

    const Test tt;
	//()表达式
	decltype (tt.num)bb1;//int-类表达示
	decltype ((tt.num))bb2 = x;//const int&
	cout << "bb2 = " << bb2 << endl;
	//+表达式
	int m = 44; int n = 55;
	decltype (m + n)cc1;//普通表达式-int
	decltype (m = m + n)cc2 = x;//int&

 3.返回类型后置

        auto func(参数1,参数2,·····)->decltype(表达式),auto会自动追踪decltype()推导的类型

//R为返回类型,U、V为参数类型
template<class R,typename U,class V>
R add(U u,V v){
	return u + v;
}

//返回值类型后置 auto func(参数1,参数2,·····)->decltype(表达式)
template<typename U, class V>
auto add2(U u, V v) ->decltype(u+v){
	return u + v;
}

void test_auto_decltype() {
	int a = 4;
	double b = 4.5;
	//已知模板函数的实现,当你不知道模板函数的实现时,不能使用此方式
	auto ret = add<decltype(a + b), int, double>(a,b);
	
	//返回值类型后置 auto func(参数1,参数2,·····)->decltype(表达式)
	auto ret2 = add2<int, double>(a, b);
    auto ret2 = add2(a, b);
	
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值