c++ - 类型名、类型成员和非类型成员 : is it valid code?

标签 c++ gcc clang language-lawyer typename

考虑以下代码:

struct S {
    struct type {};
    type type;
};

int main() {  
    typename S::type t;
    (void) t;
}

除了这远不是一个好主意之外,我在阅读了另一个关于 SO 的问题后进行了试验。
我发现上面的代码片段是 compiled with no errors by GCC它是rejected by clang 3.9出现以下错误:

error: typename specifier refers to non-type member 'type' in 'S'

我怀疑在这种情况下 clang 是正确的,而 GCC 是错误的(实际上,我正在向后者提出问题)。
这是正确的结论还是 typename 的有效使用?


注意:我不是在问如何解决它,我知道该怎么做。我只是问这个代码是否有效。

最佳答案

[temp.res]/4 :

The usual qualified name lookup is used to find the qualified-id even in the presence of typename.

也就是说,与elaborated-type-specifier的情况不同,这种情况下的名称查找不会忽略非类型名称。

[temp.res]/3 :

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
}

关于c++ - 类型名、类型成员和非类型成员 : is it valid code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40523513/

相关文章:

gcc - 如何让 gcc/clang 警告 switch 语句中缺少中断

c++ - Cppdepend C++ linux基础

c++ - 一个数组,其中每个元素都是一个数的约数和下一个数的约数

c++ - 是否有任何 API 可以在 Windows 中获取路径 "C:\Documents and Settings"?

c++ - Priority_queue 中的多次插入和删除

c - 链接器无法找到其他静态库中的函数

c++ - 类中的 ofstream - 试图引用已删除的函数

c++ - C++ 中对 Fortran 函数的 undefined reference

c++ - 将 OpenMP 与 clang 一起使用

xcode - 如何在 Xcode 中禁用一个文件的优化