类型名、类型成员和非类型成员:它是有效代码吗?
typename, type members and non-type members: is it valid code?
考虑以下代码:
struct S {
struct type {};
type type;
};
int main() {
typename S::type t;
(void) t;
}
除了这远不是一个好主意之外,我在阅读了另一个关于 SO 的问题后进行了试验。
我发现上面的代码片段 compiled with no errors by GCC and it is rejected by clang 3.9 有以下错误:
error: typename specifier refers to non-type member 'type' in 'S'
我怀疑clang在这种情况下是正确的,而GCC是错误的(实际上,我正在向后者提出问题)。
这是正确的结论还是 typename
的有效使用?
注意:我不是在问如何解决,我知道如何解决。我只是问这个代码是否有效。
The usual qualified name lookup is used to find the qualified-id even in the presence of typename
.
也就是说,与 elaborated-type-specifiers 的情况不同,这种情况下的名称查找不会忽略非类型名称。
If the qualified-id in a typename-specifier does not denote a type or a class template, the program is ill-formed.
所以有问题的程序格式错误。
[temp.res]/4 也有一个例子:
struct A {
struct X { };
int X;
};
struct B {
struct X { };
};
template<class T> void f(T t) {
typename T::X x;
}
void foo() {
A a;
B b;
f(b); // OK: T::X refers to B::X
f(a); // error: T::X refers to the data member A::X not the struct A::X
}
考虑以下代码:
struct S {
struct type {};
type type;
};
int main() {
typename S::type t;
(void) t;
}
除了这远不是一个好主意之外,我在阅读了另一个关于 SO 的问题后进行了试验。
我发现上面的代码片段 compiled with no errors by GCC and it is rejected by clang 3.9 有以下错误:
error: typename specifier refers to non-type member 'type' in 'S'
我怀疑clang在这种情况下是正确的,而GCC是错误的(实际上,我正在向后者提出问题)。
这是正确的结论还是 typename
的有效使用?
注意:我不是在问如何解决,我知道如何解决。我只是问这个代码是否有效。
The usual qualified name lookup is used to find the qualified-id even in the presence of
typename
.
也就是说,与 elaborated-type-specifiers 的情况不同,这种情况下的名称查找不会忽略非类型名称。
If the qualified-id in a typename-specifier does not denote a type or a class template, the program is ill-formed.
所以有问题的程序格式错误。
[temp.res]/4 也有一个例子:
struct A {
struct X { };
int X;
};
struct B {
struct X { };
};
template<class T> void f(T t) {
typename T::X x;
}
void foo() {
A a;
B b;
f(b); // OK: T::X refers to B::X
f(a); // error: T::X refers to the data member A::X not the struct A::X
}