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

类型别名(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++语言核心特性解析
posted @   machine_gun_lin  阅读(407)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示