1、C 中的 auto
表示自动存储变量,临时申请一块变量内存地址,可以对比 static 关键字,staitc 静态存储,存储在全局数据区。
例如:
auto double x = 10.2;
表示 x 为一个自动存储的临时变量。
2、C++ 中的 auto
2.1 语法规则
auto 关键字实现 自动类型推导 功能,编译器会在编译期间自动推导出变量的类型,无需手动指明变量的数据类型,例如:
auto a = 10; // a 为 int
auto b = 1.8; // b 为 double
auto c = &a; // c 为 int *
auto d = "china"; // d 为 const char *
int x = 0;
auto *p1 = &x; //p1 为 int *,auto 推导为 int
auto p2 = &x; //p2 为 int*,auto 推导为 int*
auto &r1 = x; //r1 为 int&,auto 推导为 int
auto r2 = r1; //r2 为 int,auto 推导为 int
int x = 0;
const auto n = x; //n 为 const int ,auto 被推导为 int
auto f = n; //f 为 const int,auto 被推导为 int(const 属性被抛弃)
const auto &r1 = x; //r1 为 const int& 类型,auto 被推导为 int
auto &r2 = r1; //r1 为 const int& 类型,auto 被推导为 const int 类型
2.2 常见应用
(1)定义迭代器
定义迭代器是最常见的用法。
#include <vector>
using namespace std;
int main(){
vector< vector<int> > v;
vector< vector<int> >::iterator i = v.begin();
auto j = v.begin(); //使用 auto 代替具体的类型,相比上面实现,让编译器加班,更加简单
vector<string> ll(10);
//for (auto u : ll) {;}
for (auto &u : ll) {;} //使用引用方式,访问元素,效率更高
return 0;
}
(2)泛型编程
#include <iostream>
using namespace std;
class A{
public:
static int get(void){
return 100;
}
};
class B{
public:
static const char* get(void){
return "http://c.biancheng.net/cplus/";
}
};
template <typename T>
void func(void){
auto val = T::get();
cout << val << endl;
}
int main(void){
func<A>();
func<B>();
return 0;
}
不使用 auto 实现方案:
#include <iostream>
using namespace std;
class A{
public:
static int get(void){
return 100;
}
};
class B{
public:
static const char* get(void){
return "http://c.biancheng.net/cplus/";
}
};
template <typename T1, typename T2> //额外增加一个模板参数 T2
void func(void){
T2 val = T1::get();
cout << val << endl;
}
int main(void){
//调用时也要手动给模板参数赋值
func<A, int>();
func<B, const char*>();
return 0;
}
参考:
http://c.biancheng.net/view/6984.html
https://baike.baidu.com/item/auto/10128?fr=aladdin#1