确保使用自定义类型

Ensure use of custom types

本文关键字:类型 自定义 确保      更新时间:2023-10-16

考虑到typedefs对基本类型的好处以及为什么使用它们,有什么方法可以确保在您的项目中没有使用基本类型,而是使用typedef对应的类型吗?

如果真的、绝对地想要禁止本机类型但允许typedefs,我想你总是可以这样做:

#include <stdint.h>
#define int please_use_stdint_typedefs_rather_than_native_types
int main()
{
    int32_t good;  // Good typedef.
    int evil;      // Evil native type.
}

$ gcc -c int_forbidden.c 
int_forbidden.c: In function ‘main’:
int_forbidden.c:8: error: ‘please_use_stdint_typedefs_rather_than_native_types’ undeclared (first use in this function)
int_forbidden.c:8: error: (Each undeclared identifier is reported only once
int_forbidden.c:8: error: for each function it appears in.)
int_forbidden.c:8: error: expected ‘;’ before ‘evil’

也就是说,我认为在一般情况下,彻底禁止原生类型不是一个好主意。

您可以按照这个boost库中的建议,使这些类型定义成为强类型定义:http://www.boost.org/doc/libs/1_40_0/boost/strong_typedef.hpp

考虑到typedef只是一个类型的同义词,实际上并没有创建一个新类型,我认为没有任何可靠的方法来确保这一点。您可以编写一个脚本来运行代码,并查找基元类型与预期的typedef对应类型的出现情况。