using定义模板别名

typedef:一般用来定义别名

typedef unsigned int uint_t;
uint_t abd;//unsigned int

再来看看以下代码

#include <iostream>
#include <map>

int main()
{
	typedef unsigned int uint_t;
	uint_t abd;//unsigned int

	typedef std::map<std::string, int> map_s_i;
	map_s_i mymap;
	mymap.insert({ "first",1 });
	mymap.insert({ "second", 2 });

	typedef std::map<std::string, std::string>map_s_s;
	map_s_s mymap2;
	mymap2.insert({ "first","firstone" });

	return 0;
}

map是一种包含键和值的容器,编译没有问题,但是现在我有这样一个需求,需要前面键固定,值的类型可变(主要是方便一点点),以下实现

//c++98
#include <iostream>
#include <map>

template <typename wt>
struct map_s
{
	typedef std::map<std::string, wt>type;
};

int main()
{
	map_s<int>::type map1;
	map1.insert({ "first",1 });

	return 0;
}

随着c++11版本的到来,解决以上问题看以下代码

//c++11
#include <iostream>
#include <map>

template<typename T>
using map_s = std::map<std::string, T>;

int main()
{
	map_s<int> map1;
	map1.insert({ "first",1 });

	return 0;
}

这里的using是用来给一个"类型模板"起名字(别名)用的。using在用于 定义类型(定义类型模板) 的时候,是包含了typedef的所有功能的。

typedef unsigned int uint_t;
using uint_t = unsigned int;

typedef std::map<std::string, int>map_s;
using map_s = std::map<std::string, int>;

在之前博客中用typedef定义过函数指针,博客链接。用using的写法如下

typedef int(*FuncType)(int , int);//用typedef来定义指针 ,看上去像定义变量
using FuncType = int(*)(int ,int);//using看上去像赋值
#include <iostream>
#include <map>

using namespace std;

template<typename T>
using myfunc_M = int(*)(T, T);//定义类型模板, 是一个函数指针模板

int func(int i, int j)
{
	return i + j;
}

int main()
{
	myfunc_M<int> pointFunc;//myfunc_M是一个函数指针类型, 是一个类型名
							//pointFunc是一个函数指针
	pointFunc = func;
	cout << pointFunc(1, 3) << endl;

	return 0;
}
4

using中使用这种模板,既不是类模板,也不是函数模板,我们可以看成是一种新的模板类型(类型模板/模板别名)。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值