decltype() is different from the auto keyword. We declare a variable in auto and we have to give it a first value.
decltype() corresponds to a type.
There are 2 separate sets of rules for decltype().
1) decltype(name)
Examples ;
decltype(x)
decltype(x.y)
decltype(ptr->a)
/*The compiler will look at what the type for this name is and think that-
the type obtained with decltype is that type.*/
int ival; decltype(ival) x; -----> int x;
double dval; decltype(dval) x; -----> double x;
struct Data{
int mx;
};
Data data; decltype(data.mx) x; -----> int x;
Data *p=&data; decltype(p->mx) x; -----> int x;
Note : We can use decltype wherever we use type because decltype means type.
Note: const is ignored in auto keyword, but const is not ignored in decltype.
const int cx=10; decltype(cx) y=10; -----> const int y=10;
Note: reference(&) is ignored in auto keyword, but reference(&) is not ignored in decltype.
int x=10;
int &r=x;
decltype(r) foo(); -----> int& foo();
int x=10;
const int &r=x;
decltype(r) y=x; -----> const int& y;
Note:No array to pointer conversion (array decay) in decltype.
int a[] {1,2,3,4};
decltype(a) b; -----> int b[4];
2) decltype(expression)
decltype (x) -----> 1. Rule set
decltype ((x)) -----> 2. Rule set
All of the examples below will apply the 2nd rule set, so it's no longer a name but an expression.
decltype (10);
decltype (x+5);
decltype (x++);
decltype ((y));
decltype (*ptr);
decltype (a[5]);
Note: In this rule set, type inference depends on whether the expression is Lvalue, Rvalue, or Xvalue.
Note: If the expression is a PRValue expression, the resulting type is directly the type of that expression.
decltype(10) x; // x is int.
int x=20;
decltype(x+4.5) dval; // dval is double.
Note: If the operand of the decltypeoperator is not a name,if expression is in value category PRvalue expression, the type obtained with decltype is type T.If the expression is in the Lvalue expression value category, the type obtained with decltype is T&.If the expression is in the Xvalue expression value category, the type obtained with decltype is T&&.
If the expression is an Lvalue expression, examples of its status are given below.
int x=20;
decltype(++x) y=x; -----> int & y;
int x=20;
int *ptr=&x;
decltype(*ptr) y=x; -----> int & y;
int a[10] [20] {};
decltype (a[2][5]) ----->int &;
int x=10;
decltype(x) -----> int
decltype((x)) -----> Since the variable x is an Lvalue, the type of the expression is int&.
Note: The compiler does not generate an opcode for the expression that is the operand of the decltype operator
int x=20;
decltype(x++) y=45; -----> y is int.
decltype(++x) y=x; -----> Since ++x is an Lvalue y is int&. x=20 because the compiler does not generate an opcode for the expression that is the operand of the decltype operator