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

时间:2022-07-24
本文章向大家介绍C++核心准则T.43: 定义别名时,using比typedef更好,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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(示例)

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