I have started learning C++ from the book C++ primer. In that book, the autor says that decltype will return a reference with dereference operator. Sorry if I am confusing here. I will give a code:
1 2 3
int v = 1;
int *p = &v;
// decltype(*p) will yeild the type int& not int.
I am confused. The book does not really tell the issue here. Dereferencing the pointer p will give the object v which has a type int. Why is it returning type int& then? In which cases will it return types like that?
int main()
{
int v = 0 ;
int*p = &v ;
decltype(v) a = 0 ; // v is the name of an object of type int; type is int
decltype( (v) ) b = a ; // (v) is an expression of type int; value category of the expression is lvalue
// type is lvalue reference to int (int&)
decltype(*p) c = a ; // (*p) is an expression of type int; value category of the expression is lvalue
// type is lvalue reference to int (int&)
decltype( +*p ) d = b+c ; // (+*p) is an expression of type int; value category of the expression is prvalue
// type is int
int foo() ;
decltype( foo() ) e = c+d ; // foo() is an expression of type int; value category of the expression is prvalue
// type is int
int& bar() ;
decltype( bar() ) f = a ; // bar() is an expression of type int; value category of the expression is lvalue
// type is lvalue reference to int (int&)
int&& baz() ;
decltype( baz() ) g = a + 8 ; // baz() is an expression of type int; value category of the expression is xvalue
// type is rvalue reference to int (int&&)
}