using
3. using
1. 定义别名
// 使用typedef定义函数指针
typedef int(*func_ptr)(int, double);
// 使用using定义函数指针
using func_ptr1 = int(*)(int, double);
效果是一样的,但是使用using更加清晰
2. 模板的别名
typedef对模板的别名简单并不容易实现
template <typename T>
typedef map<int, T> type; // error, 语法错误
#include <iostream>
#include <functional>
#include <map>
using namespace std;
template <typename T>
// 定义外敷类
struct MyMap
{
typedef map<int, T> type;
};
int main(void)
{
MyMap<string>::type m;
m.insert(make_pair(1, "luffy"));
m.insert(make_pair(2, "ace"));
MyMap<int>::type m1;
m1.insert(1, 100);
m1.insert(2, 200);
return 0;
}
在C++11中,新增了一个特性就是可以通过使用using来为一个模板定义别名
template <typename T>
using mymap = map<int, T>;
#include <iostream>
#include <functional>
#include <map>
using namespace std;
template <typename T>
using mymap = map<int, T>;
int main(void)
{
// map的value指定为string类型
mymap<string> m;
m.insert(make_pair(1, "luffy"));
m.insert(make_pair(2, "ace"));
// map的value指定为int类型
mymap<int> m1;
m1.insert(1, 100);
m1.insert(2, 200);
return 0;
}
再次强调,using的语法和typedef是一样的,并不会创建新的类型,只是定义别名, using相较于typedef的优势在于定义函数指针别名时看起来更加直观,并可给模板定义别名。