C++11:(六)C++11使用using定义别名(替代typedef)

C++98/03

C++ 中可以通过 typedef 重定义一个类型:typedef unsigned int uint_t;

但是无法重定义一个模板。所以不得不这么写:

template<typename Val>
struct str_map
{
    typedef map<string, Val> type;
}
//使用
str_map<int>::type map1;  //必须加个str_map<int>外敷类

C++11

using别名语法它来了!它来了!

template<typename Val>
using str_map_t = map<string, Val>;   //using重定义的即不是类模板也不是函数模板,也是一个模板别名

str_map_t<int> map1;  //可以不用写str_map<int>::str_map_t<int> map1

总结

普通类型的重定义对比:using比typedef语法更清晰。

// 重定义unsigned int
typedef unsigned int uint_t;
using uint_t = unsigned int;
// 重定义std::map
typedef map<string, int> map_int_t;
using map_int_t = map<string, int>;

看看新的using语法如何定义模板别名:

/* C++98/03 */
template <typename T>
struct func_t{
  	typedef void (*type)(T,T);  
};
//使用func_t模板
func_t<int>::type xx_1;

/* C++11 */
template<typename T>
using func_t = void(*)(T,T);  //using重定义的即不是类模板也不是函数模板,也是一个模板别名
//使用func_t模板
func_t<int> xx_2;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值