[C++11]使用using和typedef给模板定义别名

本文探讨了using关键字在模板类型定义上的优势,对比了它与typedef的区别,重点介绍了如何使用using为模板创建直观的别名,以及在实际代码中的应用实例。

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

using语法和typedef一样,并不会创建出新的类型,它们只是给某些类型定义了新的别名。using相较于typedef的优势在于定义函数指针别名时看起来更加直观,并且可以给模板定义别名。

使用typedef给模板定义别名:

无法直接使用typedef给模板定义别名

代码如下:

template<typename T>
typedef map<int, T>mapType;//error

注意:使用typedef给模板定义别名,需要用到struct

代码如下:

#include <iostream>
#include <string>
#include <map>
using namespace std;

template<typename T>
struct myMap
{
	typedef map<int, T>mapType;
};


template<typename T>
class Container
{
public:
	void print(T & t)
	{
		auto it = t.begin();
		for (; it != t.end(); it++)
		{
			cout << it->first << " " << it->second << endl;
		}
	}
};

int main()
{
	myMap<int>::mapType mm1;
	mm1.insert(make_pair(1, 1));
	mm1.insert(make_pair(2, 2));
	mm1.insert(make_pair(3, 3));

	Container<myMap<int>::mapType> q;
	q.print(mm1);

	myMap<double>::mapType mm2;
	mm2.insert(make_pair(1, 1.1));
	mm2.insert(make_pair(2, 2.2));
	mm2.insert(make_pair(3, 3.3));

	Container<myMap<double>::mapType> q1;
	q1.print(mm2);

	myMap<string>::mapType mm3;
	mm3.insert(make_pair(3, "Tom"));
	mm3.insert(make_pair(2, "Jack"));
	mm3.insert(make_pair(1, "Hello"));

	Container<myMap<string>::mapType> q2;
	q2.print(mm3);

	return 0;
}

测试结果:

在这里插入图片描述

使用using给模板定义别名:

代码如下:

#include <string>
#include <iostream>
#include <map>
using namespace std;


template<typename T>
class Container
{
public:
	void print(T & t)
	{
		auto it = t.begin();
		for (; it != t.end(); it++)
		{
			cout << it->first << " " << it->second << endl;
		}
	}
};


template<typename T>
using myMap = map<int, T>;


int main()
{
	myMap<string> mm3;
	mm3.insert(make_pair(1, "Tom"));
	mm3.insert(make_pair(2, "jack"));
	mm3.insert(make_pair(3, "hello"));
	Container<myMap<string>> t;
	t.print(mm3);
	return 0;
}

测试结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值