Search code examples
c++type-conversiondecltype

Different types of `decltype((const int)a)` and `decltype((const int)1)`


// g++ 7.3
template<typename T>
struct td;

int main()
{
  int a = 1;

  td<decltype((const int)a)> t1;
  td<decltype((const int)1)> t2;

  return 0;
}

Below is the output of compilation:

error: aggregate ‘td<int> t1’ has incomplete type and cannot be defined
error: aggregate ‘td<const int> t2’ has incomplete type and cannot be defined

So, why are the types of decltype((const int)a) and decltype((const int)1) different?


Solution

  • The specifiers decltype((const int)a) and decltype((const int)1) both resolve to int. This is because there are no const prvalues of non-class type, as covered in C++17 [expr]:

    If a prvalue initially has the type cv T, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

    Your output might just be a bug in the diagnostic message. To confirm a compiler bug you could write some code whose behaviour differs depending on the decltype result, e.g.:

    decltype((const int)1) x;  x = 5;
    

    which should compile successfully.