这段代码在 C++20 中编译(使用 gcc 10.1),没有使用typename
依赖类型之前的关键字std::vector<T>::iterator
。为什么它能编译?
#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>;
}
代码游乐场 https://godbolt.org/z/WhSs53
C++20 的新特性之一是打倒typename http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0634r3.html.
In C++17, you had to provide the typename
keyword in nearly all† dependent contexts to disambiguate a type from a value. But in C++20, this rule is relaxed a lot. In all contexts where you need to have a type, the typename
keyword is no longer mandatory.
其中一种上下文是类范围内函数的返回类型,如您的示例所示。其他包括成员声明中的类型、using 声明右侧的类型、lambda 的参数声明、您要传递给的类型static_cast
等。完整列表请参阅论文。
† Nearly all because base-specifiers and mem-initializer-ids were always excluded, as in:
template <typename T> struct X : T::type { }; // always ok
这没关系,因为,嗯,那needs成为一种类型。这篇论文只是将这个逻辑(好吧,它必须是一种类型,所以我们假设它是一种类型)扩展到更多必须是类型的地方。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)