The use of auto in C++11

introduction

Auto represents variables with automatic storage duration in the old c++ standard, and auto is described as a separate knowledge point in c++11, which is no longer the previous role. In c++11, it is used for automatic type inference.

example

Since auto is used for automatic type inference, how is it used. Let's look at its use with a few examples.

example one

auto  a = 3;//auto为int类型
auto  b = 2.34;//auto为double类型
auto c = 'd';//auto为char类型

Example two

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*

Notice

auto is used for type inference, but there are still some restrictions when using it.
1.auto cannot be used for function parameters

void fun(auto a){
    
    //error:auto不能用于函数参数
//do something
}

2.auto cannot have non-static member variables

class A{
    
    
auto m_a = 0;//error:auto不能用于非静态成员变量
static auto m_b = 0;//ok
int *p = nullptr;//ok
}

C++11 can accept in-place initialization of non-static member variables, but does not support the initialization of non-static member variables of auto type.
3.auto cannot define an array

int array[2]={
    
    0};
auto arr[2] = array;//auto不能定于数组

4. auto cannot infer template parameters

template<typename T>  
struct Bar{
    
    };
int main(){
    
    
	Bar<int> bar;
	Bar<auto> b = bar;//error不能进行模板参数推断
}

5. Auto must be initialized when used

std::string str = "hello";
auto a = str;
auto b;//error无法进行类型推断,必须进行初始化

use auto

The precautions for using auto have been described, so when should auto be used? Let’s record some scenarios in the use of auto.

scene one

It can be used when traversing containers and defining iterators.

std::map<int,int> iMap;
for(auto it = iMap.begin();it != iMap.end();++it){
    
    
	//do something
}

scene two

Used when simplifying function definitions.

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;
}

The function template uses auto to call the corresponding function according to the type of T in the function to infer, thus simplifying the writing of the function.
The above is the use of auto in C++11.

Guess you like

Origin blog.csdn.net/blqzj214817/article/details/127297494