Search code examples
c++language-lawyerautodecltypec++17

Are cv-qualifiers allowed on decltype(auto) variables?


The standard states that

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone.

decltype(auto)*x7d = &i; // error, declared type is not plain decltype(auto)

It is not clear whether cv-qualifiers are still allowed though. It would make sense if they are allowed. Compilers seem to disagree on this matter. The following code is accepted by g++ but rejected by clang++, vc++ does not seem to support decltype(auto) variables at all:

int main()
{
    const decltype(auto) sz_text{"test"};
}

Solution

  • To answer that, we need to quote the previous paragraph, which specifies what T is. In this case, [dcl.type.auto.deduct]/2 says (emphasis mine):

    A type T containing a placeholder type, and a corresponding initializer e, are determined as follows:

    • for a variable declared with a type that contains a placeholder type, T is the declared type of the variable and e is the initializer. If the initialization is direct-list-initialization, the initializer shall be a braced-init-list containing only a single assignment-expression and e is the assignment-expression;

    In this case, T is the whole declared type of sz_text, cv-qualifiers and all. And the paragraph you quoted is quite clear that if it contains decltype(auto) as placeholder, it must be that and nothing more.

    So a GCC bug. And an already reported one.