C++ alias template

本文介绍了C++中的type alias,包括typedef和using两种方式,用于为复杂类型创建别名。虽然它们功能相似,但typedef无法与template结合使用。在需要自定义模板类型时,using与alias template相结合能提供更大的灵活性,例如在定义自定义array类型的场景中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

type alias

type alias就是将某一个type重新命名为另一个更加直观简单的名字。C++中有两种type alias:

typedef

typedef [original-type] [your-alias];
比如:

typedef int Pixel;
Pixel p = 1;  // 等价于 int p = 1;

typedef std::map<std::string, std::vector<std::string>> Map;
Map m;  // 等价于std::map<std::string, std::vector<std::string>> m;

using

using [your-alias] = [original-type];
比如:

using Pixel = int;
Pixel p = 1; // 等价于int p = 1;

using Map = std::map<std::string, std::vector<std::string>>;
Map m;

typedef和using的区别

在这里,typedef和using都可以用来将int命名为Pixel,实现的功能是完全一样的。
但是,typedef不能和template一起使用。
比如当使用Map来创建instance的时候,只能创建类型为std::map<std::string, std::vector<std::string>>的Map,而不能创建类型为std::map<int, std::vector<int>>的Map,因为一开始就定义好了Map的类型。

Map m;// m can never be std::map<int, std::vector<int>>

如果想自定义传给std::map<>的类型,需要使用template,而只有using才可以使用template:

template<typename T1, typename T2>
using Map = std::map<T1, std::vector<T2>>;

Map<std::string, int> m1; 
// std::map<std::string, std::vector<int>> m1;

Map<int, float> m2;
//std::map<int, std::vector<float>> m2;

alias template:

首先,假设有一个自定义的array类型,array的数据类型是T,默认是int,size是sz

template<auto sz, typename T = int>
struct Array{
	T arr[sz];
};

template<auto sz, typename T = int>
using MyArray = Array<sz, T>

int main(){
	MyArray<3>* arr1 = new Array<3>(); // Array with int type, size = 3
	MyArray<3, double>* arr2 = new Array<3, double> // Array with double type, with size = 3;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值