C++核心准则T.43: 定义别名时,using比typedef更好

2020-09-10 10:43:54 浏览数 (4)

T.43: Prefer using over typedef for defining aliases

T.43: 定义别名时,using比typedef更好

Reason(原因)

Improved readability: With using, the new name comes first rather than being embedded somewhere in a declaration. Generality: using can be used for template aliases, whereas typedefs can't easily be templates. Uniformity: using is syntactically similar to auto.

提高可读性:使用using,新名称最先出现,而不是嵌入在声明的某个地方。通用性:using可以用于模板别名,然而typedef无法简单地用于模板。统一性:using在句法上和auto相似。

Example(示例)

代码语言:javascript复制
typedef int (*PFI)(int);   // OK, but convoluted

using PFI2 = int (*)(int);   // OK, preferred

template<typename T>
typedef int (*PFT)(T);      // error

template<typename T>
using PFT2 = int (*)(T);   // OK
Enforcement(实施建议)
  • Flag uses of typedef. This will give a lot of "hits" :-(
  • 标记使用typedef的地方。会有发现大量使用typedef的代码:-(

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t42-use-template-aliases-to-simplify-notation-and-hide-implementation-details

1 人点赞