auto的限制
auto不能用于函数参数;不支持auto类型非静态成员初始化;auto无法定义数组;auto无法推导出模板类型。
void func(auto k = 1); //auto不能用于函数参数
struct Foo
{
auto var1_ = 0; //auto不能用于非静态成员
static const auto var2_ = 0;
};
template<typename T>
struct Bar{};
int main()
{
int x = 5;
auto y = x; //auto->int,y->int
auto *a = &x; //auto->int, a->int*
auto b = &x; //auto->int *, b->int*
auto &c = x; //auto->int; c->int&
auto d = &c; //auto->int*; d->int *
const auto& g = x; //auto->int&; g->const int&
auto h = g; //auto->const int&; h->const int&
//当申明指针或者引用时,auto的推导结果将保持初始化表达式的cv属性
int arr[10] = { 0 };
auto cpArr = arr; //auto->int *;cpArr->int *
auto nextArr[10]; //auto无法定义数组
Bar<int> bar;
Bar<auto> bb = bar; //auto无法推导出模板类型
return 0;
}
auto的应用
1.无法知道变量应该被定义成什么 类型。
class Foo
{
public:
static int get()
{
return 0;
}
};
class Bar
{
public:
static const char* get()
{
return "0";
}
};
template<typename T>
func<T>()
{
auto val = T::get();
}
int main()
{
func<Foo>();
func<Bar>();
return 0;
}
2.简化变量声明类型
int main()
{
std::map<double, double> resultmap;
std::map<double, double>::iterator it = resultmap.begin();
for (; it != resultmap.end(); it++)
{
//do something
}
return 0;
}
上述代码中it的类型其实通过resultmap.begin()即可知道,因此声明可以简化如下
int main()
{
std::map<double, double> resultmap;
/*std::map<double, double>::iterator it = resultmap.begin();*/
for (auto it = resultmap.begin() ;it != resultmap.end(); it++)
{
//do something
}
return 0;
}