引言
auto在c++旧的标准中代表自动存储期的变量,而c++11中将auto作为单独的一个知识点来讲述,不再是以前的作用,c++11中它用于自动类型推断。
示例
既然auto用于自动类型推断,那么它如何使用呢。接下来通过几个示例来看它的使用。
示例一
auto a = 3;//auto为int类型
auto b = 2.34;//auto为double类型
auto c = 'd';//auto为char类型
示例二
int a = 5;
auto b = &a;//auto为int*
auto &c = a;//auto为int
const int d = 8;
auto& = d;//auto为const int
const auto e = &d;//auto为int*
注意
auto用于类型推断,但使用时依旧有一些限制。
1.auto不能用于函数参数
void fun(auto a){
//error:auto不能用于函数参数
//do something
}
2.auto不能非静态成员变量
class A{
auto m_a = 0;//error:auto不能用于非静态成员变量
static auto m_b = 0;//ok
int *p = nullptr;//ok
};
C++11中可以接受非静态成员变量的就地初始化,但不支持auto类型的非静态成员变量的初始化。
3.auto不能定义数组
int array[2]={
0};
auto arr[2] = array;//auto不能定于数组
4.auto不能推断模板参数
template<typename T>
struct Bar{
};
int main(){
Bar<int> bar;
Bar<auto> b = bar;//error不能进行模板参数推断
}
5.auto使用时必须初始化
std::string str = "hello";
auto a = str;
auto b;//error无法进行类型推断,必须进行初始化
使用auto
auto使用时的注意事项已经讲述,那么auto该在什么时候使用呢,下面记录一下auto 使用场景中的一些场景。
场景一
在容器遍历,定义迭代器的时候可以使用。
std::map<int,int> iMap;
for(auto it = iMap.begin();it != iMap.end();++it){
//do something
}
场景二
简化函数定义时使用。
class A{
public:
static int get()
{
return 0;
}
};
class B{
public:
static const char* get()
{
return "0";
}
};
template<typename T>
void fun()
{
auto ret = T::get();
}
int main()
{
fun<A>();
fun<B>();
return 0;
}
通过函数模板在函数内部采用auto根据T的类型调用相应的函数来推断,从而简化了函数的编写。
以上是C++11中auto的使用。