【C++ 学习 ㉝】- C++11 使用 using 定义别名

众所周知,在 C++ 中可以使用 typedef 定义类型别名,例如:

typedef unsigned int u_int;
typedef void(*pf)(int, int);

但它也有一些限制,比如,无法定义类模板别名。当我们需要实现一个 key_type 固定为 string,mapped_type 可能为 string、int 等的 map_str 类模板时,直接使用 typedef 是行不通的,往往不得不按以下方式去写:

#include <map>
#include <string>
#include <iostream>
using namespace std;
​
template<class T>
struct map_str
{
    typedef map<string, T> type;
};
​
int main()
{
    map_str<string>::type dictMap;
    dictMap.insert({ "hello", "你好" });
    dictMap.insert({ "world", "世界" });
    for (const auto& kv : dictMap)
    {
        cout << kv.first << " : " << kv.second << endl;
    }
​
    string fruits[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
        "苹果", "香蕉", "苹果", "香蕉" };
    map_str<int>::type countMap;
    for (const auto& e : fruits)
    {
        ++countMap[e];
    }
    for (const auto& kv : countMap)
    {
        cout << kv.first << " : " << kv.second << endl;
    }
    return 0;
}

在 C++11 中,不仅可以使用 using 定义类型别名,还可以定义类模板别名

using u_int = unsigned int;
using pf = void(*)(int, int);
// 与 typedef 相比,using 后面总是立即出现类型别名,
// 之后使用类似赋值语法,将现有的类型名赋给新的类型别名
​
template<class T>
using map_str = map<string, T>;
​
int main()
{
    map_str<string> dictMap;
    map_str<int> countMap;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值