author: hjjdebug
date: 2025年 05月 28日 星期三 12:54:25 CST
descrip: c/c++类型别名定义:
文章目录
- 1. #define 是宏替换.
- 2. c风格的typedef 通用形式 typedef type_orig alias
- 3. c++风格的using 为类型定义别名的一般格式: using alias = type_orig
- 4. using 的优点: 可以直接使用模板类型,
- 5.测试代码, 顺便测试一下引用折叠.
#define, typedef, using 都可以定义类型别名.
1. #define 是宏替换.
它可以定义任何东西,不只是类型,实现以简单换复杂.
带参宏也可以定义非常复杂的替换.
缺点是编译器只是进行字符串替换. 编译期无类型检查.复杂定义时逻辑不清晰,
c格式的typedef和c++格式的using 才是专门为类型定义别名而生.
2. c风格的typedef 通用形式 typedef type_orig alias
例如:
typedef unsigned int u_int;
typedef int(*add)(int i1,int i2);
3. c++风格的using 为类型定义别名的一般格式: using alias = type_orig
例如:
using u_int=unsigned int;
using add=int(*)(int i1,int i2);
4. using 的优点: 可以直接使用模板类型,
例如:
template
using Vec = std::vector;
typedef 不能直接使用模板类型.
例如:
template
typedef T&& doubleR; // error: template declaration of ‘typedef’
typedef 要想使用模板类型,只能外包装一个类才可以使用.
例如:
template
struct DoubleRefHelper {
typedef T&& type; // 在类模板中用typedef定义别名, 小名type是属于类的.
};
5.测试代码, 顺便测试一下引用折叠.
$ cat main.cpp
#include <stdio.h>
//模板类中, using 更方便,可直接使用模板类型, typedef还要定义在类模板中
template <typename T>
using DoubleRef = T&&; //T 可以直接使用/*template <typename T>typedef T&& doubleR; // error: template declaration of ‘typedef’*/
template <typename T>
struct DoubleRefHelper {typedef T&& type; // 在类模板中用typedef 使用模板类型定义别名
};int main()
{ //引用类型推导规则.DoubleRef<int> x = 3; // int + &&实际类型为 int&&(折叠后)DoubleRef<int&> y = x; // int & + &&实际类型为 int&(折叠后)DoubleRef<int&&> z = 5; // int && + &&实际类型为 int&&(折叠后)printf("x:%d,y:%d,z:%d\n",x,y,z);// 使用时需加class_name和::type, 小名type是属于类的.DoubleRefHelper<int>::type i = 8; // 等价于int&&printf("i:%d\n",i);return 0;
}
执行结果:
$ ./tt
x:3,y:3,z:5
i:8