2

Very simple question, I'm unable to google out the answer.

For example:

int a = 0;
int& b = x;
int&& c = 1;

decltype((a)) x; // what is the type of x?
decltype((b)) y; // what is the type of y?
decltype((c)) z; // what is the type of z?

Maybe I should assign x,y and z to some value to get different results, I'm not sure.

EDIT: According to site below double brackets turn example int into a reference: https://github.com/AnthonyCalandra/modern-cpp-features#decltype

int a = 1; // `a` is declared as type `int`
int&& f = 1; // `f` is declared as type `int&&`
decltype(f) g = 1; // `decltype(f) is `int&&`
decltype((a)) h = g; // `decltype((a))` is int&
Evg
  • 25,259
  • 5
  • 41
  • 83

3 Answers3

7

All of them are of type int&.

Adding parentheses like (a) makes them expressions (instead of entity), which are all lvalues (as named variables); then decltype yields to T&, i.e. int& here.

...

4) If the argument is any other expression of type T, and

...

b) if the value category of expression is lvalue, then decltype yields T&;

...

You can check the actual types with this LIVE DEMO (from the compiling error messages).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
5

According to C++ Primer:

When we apply decltype to a variable without any parentheses, we get the type of that variable. If we wrap the variable’s name in one or more sets of parentheses, the compiler will evaluate the operand as an expression. A variable is an expression that can be the left-hand side of an assignment. As a result, decltype on such an expression yields a reference:

// decltype of a parenthesized variable is always a reference
decltype((i)) d; // error: d is int& and must be initialized
decltype(i) e;   // ok: e is an (uninitialized) int
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
4

Note that if the name of an object is parenthesized, it is treated as an ordinary lvalue expression, thus decltype(x) and decltype((x)) are often different types.

https://en.cppreference.com/w/cpp/language/decltype

As far as I understand, (x) is an empty expression which returns a reference to x. Thus

  • decltype(x) is int
  • declytpe((x)) is int&
Evg
  • 25,259
  • 5
  • 41
  • 83
Narase
  • 490
  • 2
  • 12