C++ 可以用 typedef 为很长的类型名 type-id 起个别名 identifier:
typedef type-id identifier;
其中 type-id 是已有的类型名,identifier 是我们为它起的别名。
例子:
typedef std::map::const_iterator map_const_iter;
map_const_iter iter;
C++11 允许使用 using 来起类型别名:
using identifier = type-id;
例子:
using map_const_iter = std::map::const_iterator;
map_const_iter iter;
可以发现用 using 起类型别名有点像赋值,除此以外似乎和 typedef 没有多大区别。
实际上,using 的优势体现在对函数指针类型起别名:
typedef void(*func1)(int, int);
using func2 = void(*)(int, int);
可以发现使用 using 的别名要更清晰。
C++11 还可以通过 using 使用别名模板。
别名模板的本质也是一个模板。
只是在实例化的过程中用自己的模板参数替换原始模板的参数,并实例化原始模板。
例子:
#include
#include 这里 int_map 是一个类型的别名,并且用到了模板。
在实例化的时候,只需要传需要的一个模板参数(这里是 std::string)替换原始模板中的对应类型,所以这里 int_map 就相当于 std::map:
linrongjian@hhb-ssd:/data/modern_cpp$ g++ -std=c++11 template_alias_example.cpp -o template_alias_example
linrongjian@hhb-ssd:/data/modern_cpp$ ./template_alias_example
11