不允许使用auto的四个场景:
1.不能作为函数参数使用,因为只有在函数调用的时候才会给函数参数传递实参,auto要求必须要给修饰的变量赋值,因此二者矛盾。
代码如下:
//error
int func(auto a, auto b)
{
cout << a << " " << b << endl;
}
2.不能用于类的非静态成员变量的初始化。
代码如下:
class Test
{
auto a = 0;//error
static auto b = 2;//error,类的静态非常量成员不允许在类内部直接初始化
static const auto c = 10;//ok
};
3.不能使用auto关键字定义数组。
代码如下:
int func()
{
int array[] = { 1,2,3,4,5 };//ok
auto t1 = array;//ok,t1 -> int *
auto t2[] = array;//error,auto无法定义数组
auto t3[] = { 1,2,3,4,5 };//error,auto无法定义数组
}
4.无法使用auto推导出模板参数。
代码如下:
template <typename T>
struct Test
{
};
int func()
{
Test<double> t;
Test<auto> t1 = t;//error,无法推导模板类型
return 0;
}