新简化!typename 在 C++20 不再必要
The following article is from CPP编程客 Author 里缪
根据提案P0634-Down with typename,C++20之后typename在有些地方不再必要。
If X::Y — where T is a template parameter — is to denote a type, it must be preceded by the keyword typename; otherwise, it is assumed to denote a name producing an expression. There are currently two notable exceptions to this rule: base-specifiers and mem-initializer-ids. For example:
template<class T>
struct D: T::B { // No typename required here.
};
Clearly, no typename is needed for this base-specifier because nothing but a type is possible in that context.
1#include <iostream>
2
3struct S {
4 using X = int;
5 using R = char;
6};
7
8
9// 类模板
10template<class T,
11 auto F = typename T::X{}> // 需要typename
12struct Foo {
13 using X2 = T::X; // 不需要typename
14 typedef T::X X3; // 不需要typename
15 T::X val; // 不需要typename
16
17 T::R f(T::X x) { // 不需要typename
18 typename T::X i; // 需要typename
19 return static_cast<T::R>(x); // 不需要typename
20 }
21
22 auto g() -> T::R { // 不需要typename
23 }
24
25 template<class U = T::X> // 不需要typename
26 void k(U);
27};
28
29
30// 函数模板
31template<class T>
32T::R // 不需要typename
33f(typename T::X x) // 需要typename
34{
35 using X2 = T::X; // 不需要typename
36 typedef typename T::X X3; // 需要typename
37 typename T::X val; // 需要typename
38
39 typename T::R f(); // 需要typename
40 auto g() -> T::R; // 不需要typename
41 void k(typename T::X); // 需要typename
42
43 auto lam = [](T::X) {}; // 不需要typename
44
45 return static_cast<T::R>(x); // 不需要typename
46}
47
48int main()
49{
50 Foo<S> foo;
51 f<S>(65);
52
53 return 0;
54}
- EOF -
关注『CPP开发者』
看精选C/C++技术文章
点赞和在看就是最大的支持❤️