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]