use*_*740 3 c++ language-lawyer type-alias
昨天,当我能够编译具有使用 using 类型别名的方法的代码时,我(愉快地)感到惊讶,即使别名的声明直到类定义的后期才进行。
案例 #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;
}
Run Code Online (Sandbox Code Playgroud)
案例 #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;
}
Run Code Online (Sandbox Code Playgroud)