using定义模板别名
using定义模板别名
using : 一般用来给类型定义别名
typedf unsigned int uint_t; //相当于给unsigned int 定义了一个别名uint_t
typedef std::map<std::string, int> map_s_i;
map_s_i m_val;
m_val.insert({"first", 1});
typedef std::map<std::string, std::string> map_s_s;
map_s_s m_val2;
m_val2.insert({"first", "first"});
希望第一个值类型固定,第二个类型可变
C++98给出的方案:
template<class wt>
struct map_s{ //定义了一个结构/类
typedef std::map<std::string , wt> type; //定义了一个类型,键
}
map_s<int>::type map1; //相当于定义了一个map<std::string , int> map;
map1.insert({"hello", 520});
C++11给出的方案:
template<class T>
using map_s_T = map<std::string ,T>; //map_s_T类型别名
map_s_T<int> map2;
map2.insert({"second", 1}); //using给一个“类型模板”起别名
//using 定义类型(定义类型模板)是包含了typedef功能的。
typedf unsigned int uint_t;
using uint_t = nsigned int;
typedef int(*FuncTyppe)(int , int); //类似于定义变量 类型 变量名
using FuncType = ine(*)(int , int); //类似于赋值运算式
template<class T>
using myfunc_M = int(*)(T, T); //定义类型模板,为一个函数指针模板
int test_M(int ,int){
return 1;
}
myfunc_M<int> pointFunc; //myfunc_M<int>是一个类型,pointFunc是一个函数指针变量
pointFunc = test_M; //把函数地址赋给函数指针变量
std::cout << pointFunc(1,6) <<std::endl;
using 使用这种模板既不是类模板,也不是函数模板,是一种新的模板:类型模板(或者模板别名)
显式指定模板参数
template<class T1; class T2 ; class T3>
T1 sum(T2 i, T3 j){
result = i + j;
return result;
}
auto ret = sum<double,double,double>(200000000, 200000000); //显示指定返回类型,手动指定类型优先