日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

[C++11]使用using和typedef给模板定义别名

發布時間:2023/12/4 c/c++ 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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给模板定义别名的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。