using定義模板別名
-
using
//typedef:一般用來定義類型別名 typedef unsigned int uint_t; uint_t abc; //map<string, int> typedef map<string, int> hashmap; hashmap m; m.insert({ "first", 1 }); //map<string, string> typedef map<string, string> hashmap_ss;
-
定義一個map類型,key是string類型,不變,value的類型可以自己指定
-
C++98
#include <iostream> #include <map> #include <string> using namespace std; //c++98 template <typename st> struct map_s //定義了一個結構;結構成員的缺省都是public { typedef map <string, st> type;//定義了一種類型 }; int main() { map_s<int>::type map; return 0; }
-
C++11
#include <iostream> #include <map> #include <string> using namespace std; //C++11 template <typename T> using str_map = map<string, T>; //str_map是類型別名 //using 給模板起別名 用來給“類型模板”起名字 //using用於定義類型的時候,包含了typedef的所有功能 int main() { str_map<int> map; map.insert({ "abc", 123 }); return 0; }
-
函數指針模板
typedef int(*FuncType)(int, int); using FuncType = int(*)(int, int);
#include <iostream> #include <map> #include <string> using namespace std; template <typename T> using myfunc_M = int(*)(T, T); //定義類型模板 函數指針模板 int RealFunc(int i, int j) { cout << i + j << endl; return 1; } int main() { myfunc_M<int> pointFunc = RealFunc; pointFunc(1, 2); return 0; }
顯式指定模板參數
#include <iostream>
#include <map>
#include <string>
using namespace std;
template <typename T1, typename T2, typename T3>
T1 sum(T2 i, T3 j)
{
T1 res = i + j;
return res;
}
int main()
{
//自己指定的類型優先
auto res = sum<double>(2000000000000000000, 2000000000000000000);
cout << res << endl;
return 0;
}
//無法省略模板參數
template <typename T1, typename T2, typename T3>
T3 sum(T1 i, T2 j)
{
T1 res = i + j;
return res;
}