On the difference between decltype and auto

The difference between decltype and auto
① Differences to reference variables: After auto assigns a reference variable to a variable, the type of the variable is the type of the variable corresponding to the reference variable. And decltype is a reference type. Examples are as follows:
int i = 0,&r = i;
//same
auto a = i;
decltype (i)b = i;
//different
auto c = r; c is of type int
decltype (r)d = r;//d is int & type
②The way to deal with the underlying const is different
auto will generally ignore the top-level const, while the bottom-level const will be preserved
example:
const int ci = i,&cr = ci;
auto b = ci; integer
auto c = cr; integer
auto d = &i;integer pointer
auto e = &ci; pointer to integer constant
decltype returns the full type of the variable (including top-level const and reference)
example:
const int ci = 0,&cj = ci;
decltype (ci) x = 0;const int 型
decltype (cj) y = x;const int 型
decltype (cj) z ; error, z is a reference, reference must be initialized
 
In addition, the result of decltype ((variable)) (note the double brackets) is always a reference, while the result of decltype(variable) is a reference only when the variable itself is a reference.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325161301&siteId=291194637