struct A{
int a;
};
struct B{
int b;
};
auto&& [x] = A{}; //#1
auto&& [x] = B{}; //#2
int main(){
}
在本例中,all compilers给出 x
的错误#2 与 #1 中介绍的冲突。但是,IIUC,后 C++20 工作草案标准中没有任何规则可以解释原因。首先,在我看来,#2 的声明和#1 的声明声明了同一个实体。它们对应于:
basic.scope#scope-3
Two declarations correspond if they (re)introduce the same name, both declare constructors, or both declare destructors, unless
[...]
他们根据 basic.link#8 声明相同的实体
Two declarations of entities declare the same entity if, considering declarations of unnamed types to introduce their names for linkage purposes, if any ([dcl.typedef], [dcl.enum]), they correspond ([basic.scope.scope]), have the same target scope that is not a function or template parameter scope, and either
- they appear in the same translation unit, or
- [...]
因此,就目前而言,它们声明了相同的实体,不应将它们视为潜在冲突 basic.scope#scope-4。
Two declarations potentially conflict if they correspond and cause their shared name to denote different entities([basic.link]). The program is ill-formed if, in any scope, a name is bound to two declarations that potentially conflict and one precedes the other ([basic.lookup]).
如前所述,由于它们表示相同的实体,因此它们没有潜在的冲突。
他们仍然没有违反这条规则:
basic.link#11
For any two declarations of an entity E:
- If one declares E to be a variable or function, the other shall declare E as one of the same type.
- [...]
由于此列表中未提及结构化绑定(bind),因此它们不违反此规则。类似,它们不违反单一定义规则
No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, template, default argument for a parameter (for a function in a given scope), or default template argument.
至少,根据相关规则所说,这个例子中的两个声明不应该导致任何程序格式错误。如果我没有错过其他一些规则,是否可以认为标准中的模糊性无法解释为什么在这种情况下两个结构化绑定(bind)声明相互冲突? N4861 中没有详细说明这种情况。
最佳答案
这只是 [basic.link]/11 中的一个缺失案例:如果(两个声明中的一个)声明了结构化绑定(bind),则程序格式错误。 (一个也可以只要求另一个也声明一个结构化绑定(bind),然后在 [basic.def.odr]/1 中扩展列表,但这更复杂,并且表明可以在另一个翻译单元中重新定义它。)
关于c++ - 当前的标准草案似乎无法解释为什么两个结构化绑定(bind)声明相互冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65729849/