Достаточно запутанный вопрос, но похоже, что clang
прав.
Для начала рассмотрим, как определяется тип выражения E
в decltype(E)
.
[dcl.type.decltype]/1:
For an expression E, the type denoted by decltype(E)
is defined as
follows:
- if E is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]),
decltype(E)
is the referenced type as given in the specification of the structured binding declaration;
- otherwise, if E is an unparenthesized id-expression naming a non-type template-parameter,
decltype(E)
is the type of the template-parameter after performing any necessary type deduction ([dcl.spec.auto], [dcl.type.class.deduct]);
- otherwise, if E is an unparenthesized id-expression or an unparenthesized class member access ([expr.ref]),
decltype(E)
is the type of the entity named by E. If there is no such entity, or if E names a set of overloaded functions, the program is ill-formed;
- otherwise, if E is an xvalue,
decltype(E)
is T&&, where T is the type of E;
- otherwise, if E is an lvalue,
decltype(E)
is T&, where T is the type of E;
- otherwise, decltype(E) is the type of E.
x
и y
являются glvalue, но не являются xvalue, а значит являются lvalue в соответствии с [basic.lval]/fig:basic.lval:

Таким образом, срабатывает предпоследний пункт определения типа, то есть варианты с int
отпадают сразу.
Далее, рассмотрим следующую цитату.
[expr.prim.lambda.capture]/11:
Every id-expression within the compound-statement of a
lambda-expression that is an odr-use of an entity captured by copy is
transformed into an access to the corresponding unnamed data member of
the closure type. [ Note: An id-expression that is not an odr-use
refers to the original entity, never to a member of the closure type.
However, such an id-expression can still cause the implicit capture of
the entity. — end note ] ...
В данном случае выражения не являются потенциально вычисляемыми (т.к. являются операндами decltype), а значит соответствующие переменные не являются odr-использованными. Однако важно примечание — такие выражения всё ещё могут рассматриваться в контексте лямбда-замыканий, что подтверждается следующей цитатой.
[expr.prim.id.unqual]/2:
... If the entity is a local entity and naming it from outside of an
unevaluated operand within the declarative region where the
unqualified-id appears would result in some intervening
lambda-expression capturing it by copy ([expr.prim.lambda.capture]),
the type of the expression is the type of a class member access
expression ([expr.ref]) naming the non-static data member that would
be declared for such a capture in the closure object of the innermost
such intervening lambda-expression. [ Note: If that lambda-expression
is not declared mutable
, the type of such an identifier will typically
be const qualified. — end note ] ...
Другими словами, несмотря на то что захвата не происходит, тип выражения определяется так, как будто бы захват есть. Также в примечании сказано про константность идентификатора, если лямбда не имеет спецификатора mutable
, что подтверждается следующим пунктом.
[expr.prim.labmda.closure]/4:
The function call operator or operator template is declared const
([class.mfct.non-static]) if and only if the lambda-expression's
parameter-declaration-clause is not followed by mutable
. ...
Интересно, что из-за нечёткости формулировок и разбросанности их по разным разделам стандарта (на мой взгляд) оба компилятора имеют соответствующие баг-репорты: gcc, clang. На момент 2022 года оба компилятора признали правильным поведение clang
, однако в gcc
баг до сих пор не исправлен.
(())
двойные внутриdecltype
, которые несколько меняют смысл. Это специально добавлено, чтобы добавить нюансов, или зачем?(())
- критичны. Без таких скобок бы не было никакого capture иdecltype
бы относился к внешней переменной. Именно благодаря этим скобкамdecltype
работает именно с захваченной переменной.