c/c++类型别名定义


author: hjjdebug
date: 2025年 05月 28日 星期三 12:54:25 CST
descrip: c/c++类型别名定义:



#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值