typedef改变了意义

fox*_*cub 18 c++ typedef

当我编译以下代码片段时 g++

template<class T>
class A
{};

template<class T>
class B
{
    public:
        typedef A<T> A;
};
Run Code Online (Sandbox Code Playgroud)

编译告诉我

error: declaration of ‘typedef class A<T> B<T>::A’
error: changes meaning of ‘A’ from ‘class A<T>’
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我改变typedef

typedef ::A<T> A;
Run Code Online (Sandbox Code Playgroud)

一切都很好g++.Clang ++ 3.1并不关心任何一种方式.

为什么会这样?并且是第二个行为标准?

Jes*_*ood 10

g ++是正确的,符合标准.从[3.3.7/1]开始:

在类S中使用的名称N应在其上下文中引用相同的声明,并在完成的S范围内重新评估.违反此规则不需要诊断.

typedef的前,A提到了::A,但是使用的typedef,你现在做A指的是禁止的typedef.但是,因为no diagnostic is required,铿锵也是标准的符合.

jogojapan的评论解释了这条规则的原因.对您的代码进行以下更改:

template<class T>
class A
{};

template<class T>
class B
{
    public:
        A a; // <-- What "A" is this referring to?
        typedef     A<T>            A;
};
Run Code Online (Sandbox Code Playgroud)

由于类范围如何工作,A a;变得模棱两可.

  • @foxcub:在第二种形式中你不是指'A`,你指的是`:: A`.第二种形式是正确的. (3认同)