简体   繁体   English

“使用”类范围的类型别名:[何时] 方法中的用法可以先于类型别名吗?

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

Yesterday, I was (pleasantly) surprised when I was able to compile code that had a method which used a using type alias even though the declaration of the alias was not until later in the class definition.昨天,当我能够编译具有使用 using 类型别名的方法的代码时,我(愉快地)感到惊讶,即使别名的声明直到类定义的后期才进行。

  • Is this 'forward' usage of a type-alias valid?类型别名的这种“转发”用法是否有效? (I assume it is, since Clang 5 and GCC 4.9 both work this way.) (我认为是这样,因为 Clang 5 和 GCC 4.9 都是这样工作的。)
  • What rules cover this behavior and the difference between the method body and method signature usages?哪些规则涵盖了这种行为以及方法主体和方法签名用法之间的区别?

Case #1 - using declared after method, valid inside method body (only?)案例 #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;
}

Case #2 - using declared above is [also] valid in signature案例 #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;
}

This has to do with the complete-class context .这与完整类上下文有关 When you are in the body of a member function, the class is considered complete and can use anything defined in the class, no matter where in the class it is declared.当您在成员函数的主体中时,该类被认为是完整的,并且可以使用该类中定义的任何内容,无论它在类中的何处声明。

The return type of a member function is not part of the complete-class context so you can only use names that are known about at that point in the code.成员函数的返回类型不是完整类上下文的一部分,因此您只能使用代码中当时已知的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM