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++语言核心特性解析
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值