C++ 类型别名和别名模板

196 阅读1分钟

类型别名(C++11)

C++ 可以用 typedef 为很长的类型名 type-id 起个别名 identifier

typedef type-id identifier;

其中 type-id 是已有的类型名,identifier 是我们为它起的别名。

例子:

typedef std::map<int, std::string>::const_iterator map_const_iter;
map_const_iter iter;

C++11 允许使用 using 来起类型别名:

using identifier = type-id;

例子:

using map_const_iter = std::map<int, std::string>::const_iterator;
map_const_iter iter;

可以发现用 using 起类型别名有点像赋值,除此以外似乎和 typedef 没有多大区别。

实际上,using 的优势体现在对函数指针类型起别名:

typedef void(*func1)(int, int);
using func2 = void(*)(int, int);

可以发现使用 using 的别名要更清晰。

别名模板(C++11)

C++11 还可以通过 using 使用别名模板。

别名模板的本质也是一个模板。

只是在实例化的过程中用自己的模板参数替换原始模板的参数,并实例化原始模板

例子:

#include <iostream>
#include <map>
#include <string>
​
template <typename T>
using int_map = std::map<int, T>;
​
int main() {
    int_map<std::string> int2string;
    int2string[9] = "11";
    std::cout << int2string[9] << std::endl;
    return 0;
}

这里 int_map 是一个类型的别名,并且用到了模板。

在实例化的时候,只需要传需要的一个模板参数(这里是 std::string)替换原始模板中的对应类型,所以这里 int_map<std::string> 就相当于 std::map<int, std::string>

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

参考资料

  1. 现代C++语言核心特性解析