[英]"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 类型别名的方法的代码时,我(愉快地)感到惊讶,即使别名的声明直到类定义的后期才进行。
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.