Skip to content

类型别名 ​

类型别名是为现有类型创建的一个"同义词",可以简化代码或提高可读性。

创建方式 ​

C++ 提供了两种方式来创建类型别名:typedef 和 using 。

TIP

推荐:C++11 及以后优先使用 using,语法更清晰且支持模板。

传统方式:typedef ​

cpp
typedef unsigned int uint;  // uint 是 unsigned int 的别名
typedef int* int_ptr;       // int_ptr 是 int* 别名

uint x = 42; 	  // 相当于 unsigned int x = 42;
int_ptr p = &x;	  // 相当于 int* p = &x;

现代方式:using ​

C++11 增加了 using 关键字,它比 typedef 更直观,尤其在涉及模板时优势明显。

cpp
// 语法:using 别名 = 原类型
using uint = unsigned int;
using int_ptr = int*;

常见用途 ​

1. 简化复杂类型 ​

cpp
// 繁琐
std::map<std::string, std::vector<std::pair<int, std::string>>>::iterator

// 使用别名
using StringVecPairMap = std::map<std::string, std::vector<std::pair<int, std::string>>>;
StringVecPairMap::iterator it;

2. 函数指针 ​

cpp
using Callback = void (*)(int, const std::string&);

void handler(int code, const std::string& msg) {}

Callback cb = handler;
cb(200, "OK");

3. 提高可读性 ​

cpp
using Age = int;
using Score = double;

Age age = 25;
Score score = 98.5;

// 模板别名
template<typename T>
using Vec = std::vector<T>;

Vec<int> v1;      // std::vector<int>
Vec<std::string> v2;  // std::vector<std::string

以下是 using 和 typedef 在模板别名使用中的区别:

cpp
// typedef 不能直接用于模板
typedef std::vector<int> IntVec;  // 可以,但需指定类型
typedef std::vector<T> Vec;       // 错误!typedef 不支持模板参数

// using 可以
template<typename T>
using Vec = std::vector<T>;  // 正确