[英]Why don't I need to specify “typename” before a dependent type in C++20?
This bit of code compiled in C++20 (using gcc 10.1) without using the typename
keyword before the dependent type std::vector<T>::iterator
.这段代码在 C++20 中编译(使用 gcc 10.1),在依赖类型std::vector<T>::iterator
之前没有使用typename
关键字。 Why does it compile?为什么会编译?
#include <vector>
template<typename T>
std::vector<T>::iterator // Why does this not require "typename" before it?
f() { return {}; }
int main() {
auto fptr = &f<int>;
}
One of the new features in C++20 is Down with typename
. C++20 的新特性之一是Down with typename
。
In C++17, you had to provide the typename
keyword in nearly all † dependent contexts to disambiguate a type from a value.在 C++17 中,您必须在几乎所有†相关上下文中提供typename
关键字,以消除类型与值的歧义。 But in C++20, this rule is relaxed a lot.但是在 C++20 中,这个规则放宽了很多。 In all contexts where you need to have a type, the typename
keyword is no longer mandatory.在需要类型的所有上下文中, typename
关键字不再是强制性的。
One such context is the return type of a function in class scope, as in your example.一个这样的上下文是 class scope 中 function 的返回类型,如您的示例所示。 Others include the type in a member declaration, the type on the right-hand side of a using declaration, the parameter declaration of a lambda, the type you're passing to static_cast
, etc. See the paper for the full list.其他包括成员声明中的类型、using 声明右侧的类型、lambda 的参数声明、传递给static_cast
的类型等。有关完整列表,请参阅论文。
† Nearly all because base-specifiers and mem-initializer-ids were always excluded, as in: †几乎都是因为 base-specifiers 和 mem-initializer-ids 总是被排除在外,如下所示:
template <typename T> struct X : T::type { }; // always ok
This is okay because, well, that needs to be a type.这没关系,因为,嗯,这需要是一种类型。 The paper simply extends this logic (well, it has to be a type, so let's just assume it's a type) to a lot more places that have to be types.这篇论文只是将这个逻辑(嗯,它必须是一个类型,所以我们假设它是一个类型)扩展到更多必须是类型的地方。
From the reference , from c++20, in contexts where the dependent name is unambiguously a typename, the typename
keyword is no longer needed.从 c++20 的引用中,在从属名称明确为类型名的上下文中,不再需要typename
关键字。 In particular:尤其是:
A qualified name that is used as a declaration specifier in the (top-level) decl-specifier-seq of:在以下的(顶级)decl-specifier-seq 中用作声明说明符的限定名称:
a simple declaration or function definition at namespace scope命名空间 scope 的简单声明或 function 定义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.