【C++标准】之 C++11——auto特性

C++ 11 中auto特性

             C++98/03 : 修饰自动存储期的变量

             C++11      : 自动推导类型 & 返回值占位

             ( 自动类型推导并不意味着变量类型不确定 or 在运行时确定 

                而是指变量类型在编译时可由编译器推导出来 )


一些示例代码:

1. 自动类型推导

// auto a;				// error
	// auto int a = 10;		// error
	auto a = 10;			// ok

2. 类型书写冗长时

map< int, map<int, int> > m;
	map<int, map<int, int>>::const_iterator it1 = m.begin();		// C++98/03 风格
	const auto it2 = m.begin();		// C++11 风格

	auto ptr = []()
	{
		cout << "hello" << endl;
	};

3. 使用模板

template <class T1, class T2>
void mul(T1 t1, T2 t2)
{
	auto v = t1 * t2;
}

4. 返回值占位

template <class T1, class T2>
auto add(T1 t1, T2 t2) -> decltype(t1 + t2)
{
	return t1 + t2;
}

5. auto的一些不足

A. 精度问题
auto a = numeric_limits<unsigned int>::max();
auto b = 1;			// b int类型
auto c = a + b;		// c = 0 unsigned int [overflow]



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值