C/Cpp 类型别名
typedef
typedef
是用于为类型定义别名的关键字,在C和C++中都可以使用。
最简单的用法是对基本类型起别名,例如 1
typedef int Length;
下面的是MSVC的stdint.h
中的部分源码,对基本数据类型起了意义更明确的别名
1
2
3
4
5
6
7
8typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
数组类型和指针类型可以通过typedef
起别名达到简化语法和提升可读性的目的,例如
1
2
3
4
5typedef int IntArray4[4];
typedef int Matrix3x3[3][3];
typedef int* IntPtr;
typedef int** IntPtrPtr;
使用typedef
可以为结构体定义一个别名,以简化代码的书写(少写一个
struct
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// before
struct Point{
int x;
int y;
};
struct Point p;
// after
typedef struct Point{
int x;
int y;
} Point;
Point p;
对函数指针类型本身也过于复杂了,经常会使用typedef
为其定义一个别名,以增强可读性
1
2
3
4
5
6
7typedef int (*FuncType)(int, int);
int add(int a, int b) {
return a + b;
}
FuncType f = add;
using
using
在C++中可以用于定义类型别名,相比于C语言提供的typedef
,using
具有更高的可读性和灵活性。
最基本的使用如下 1
using Length = unsigned int;
在C++中没有必要为结构体重命名,因为结构体的使用本身就很简洁了。
可以使用using
为函数指针类型起一个别名 1
2
3
4
5
6
7using FuncType = int(*)(int, int);
int add(int a, int b) {
return a + b;
}
FuncType f = add;
作为与typedef
的对比,我们考虑一个比较复杂的函数指针类型:输入一个int
和一个形如bool(*)(double)
的函数指针,返回一个std::pair<int,double>
数据,显然using
的可读性更高
1
2
3typedef std::pair<int, double> (*ComplexFuncType)(int, bool (*)(double));
using ComplexFuncType = std::pair<int, double> (*)(int, bool (*)(double));
using
可以在模板类型中使用时,用于定义模板类型的别名(typedef
不支持涉及模板类型的别名)
1
2
3
4template<typename T>
using Vec = std::vector<T>;
Vec<int> v; // std::vector<int> v;
补充:
- 现代C++建议使用
using
完全替代typedef
,以提高代码的可读性。 - 现代C++赋予
using
的功能除了这里的类型别名之外,还有很多,例如臭名昭著的using namepsace std
等。