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中使用这种模板,既不是类模板,也不是函数模板,我们可以看成是一种新的模板类型(类型模板/模板别名)。