[C++11]使用using和typedef给模板定义别名
生活随笔
收集整理的這篇文章主要介紹了
[C++11]使用using和typedef给模板定义别名
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
using語法和typedef一樣,并不會創建出新的類型,它們只是給某些類型定義了新的別名。using相較于typedef的優勢在于定義函數指針別名時看起來更加直觀,并且可以給模板定義別名。
使用typedef給模板定義別名:
無法直接使用typedef給模板定義別名
代碼如下:
template<typename T> typedef map<int, T>mapType;//error注意:使用typedef給模板定義別名,需要用到struct
代碼如下:
#include <iostream> #include <string> #include <map> using namespace std;template<typename T> struct myMap {typedef map<int, T>mapType; };template<typename T> class Container { public:void print(T & t){auto it = t.begin();for (; it != t.end(); it++){cout << it->first << " " << it->second << endl;}} };int main() {myMap<int>::mapType mm1;mm1.insert(make_pair(1, 1));mm1.insert(make_pair(2, 2));mm1.insert(make_pair(3, 3));Container<myMap<int>::mapType> q;q.print(mm1);myMap<double>::mapType mm2;mm2.insert(make_pair(1, 1.1));mm2.insert(make_pair(2, 2.2));mm2.insert(make_pair(3, 3.3));Container<myMap<double>::mapType> q1;q1.print(mm2);myMap<string>::mapType mm3;mm3.insert(make_pair(3, "Tom"));mm3.insert(make_pair(2, "Jack"));mm3.insert(make_pair(1, "Hello"));Container<myMap<string>::mapType> q2;q2.print(mm3);return 0; }測試結果:
使用using給模板定義別名:
代碼如下:
#include <string> #include <iostream> #include <map> using namespace std;template<typename T> class Container { public:void print(T & t){auto it = t.begin();for (; it != t.end(); it++){cout << it->first << " " << it->second << endl;}} };template<typename T> using myMap = map<int, T>;int main() {myMap<string> mm3;mm3.insert(make_pair(1, "Tom"));mm3.insert(make_pair(2, "jack"));mm3.insert(make_pair(3, "hello"));Container<myMap<string>> t;t.print(mm3);return 0; }測試結果:
總結
以上是生活随笔為你收集整理的[C++11]使用using和typedef给模板定义别名的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为A1无线路由器怎么安装
- 下一篇: [PAT乙级]1033 旧键盘打字(ge