众所周知,在 C++ 中可以使用 typedef 定义类型别名,例如:
- typedef unsigned int u_int;
- typedef void(*pf)(int, int);
但它也有一些限制,比如,无法定义类模板别名。当我们需要实现一个 key_type 固定为 string,mapped_type 可能为 string、int 等的 map_str 类模板时,直接使用 typedef 是行不通的,往往不得不按以下方式去写:
- #include
- #include
- #include
- using namespace std;
-
- template<class T>
- struct map_str
- {
- typedef map
type; - };
-
- int main()
- {
- map_str
::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
; -
- int main()
- {
- map_str
dictMap; - map_str<int> countMap;
- return 0;
- }