【发布时间】:2020-05-26 01:44:59
【问题描述】:
昨天,当我能够编译具有使用 using type alias 的方法的代码时,我(令人愉快地)感到惊讶,尽管别名的声明直到类定义的后面才声明。
- 这种类型别名的“前向”用法是否有效? (我认为是这样,因为 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;
}
【问题讨论】:
-
我确定某处存在欺骗,但这是因为函数体是complete-class context。
标签: c++ language-lawyer type-alias