“使用"类作用域的类型别名:[何时]方法中的用法能否优先于类型别名? [英] "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.
- 这种类型别名的转发"用法是否有效?(我想是这样,因为Clang 5和GCC 4.9都以这种方式工作.)
- 哪些规则涵盖了此行为以及方法主体和方法签名用法之间的区别?
案例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;
}
推荐答案
这与 完整类上下文 .当您处于成员函数的主体中时,该类将被视为完整的,并且可以使用该类中定义的任何内容,无论在类中的何处声明它.
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.
这篇关于“使用"类作用域的类型别名:[何时]方法中的用法能否优先于类型别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!