"using" class 范围的类型别名:[何时] 可以在方法中使用先于类型别名?

"using" type alias of class scope: [when] can usages in methods PRECEDE the type alias?

昨天,当我能够编译具有使用 using type alias 的方法的代码时,我感到(高兴地)感到惊讶,即使别名的声明直到稍后才在 class定义。

案例 #1 - 使用方法后声明,在方法体内有效(仅?)

#include <string>
#include <iostream>

struct X {
  std::string create() {     // fails to compile if Y used in signature
      return Y{"hello!"};    // compiles when Y here
  }

  using Y = std::string;     // declared at bottom
};

int main() 
{
    std::cout << X().create() << std::endl;
}

案例 #2 - 使用上面声明的在签名中[也]有效

#include <string>
#include <iostream>

struct X {
  using Y = std::string;     // declared at top

  Y create() {               // can use Y here as well
      return Y{"hello!"};
  }
};

int main() 
{
    std::cout << X().create() << std::endl;
}

这与complete-class context有关。当您在成员函数的主体中时,class 被认为是完整的并且可以使用 class 中定义的任何内容,无论它在 class 中的何处声明。

成员函数的 return 类型不是 complete-class 上下文 的一部分,因此您只能使用已知的名称代码中的那一点。