一、using定义模板别名
typedef:一般用来定义类型别名。
typedef unsigned int uint_t; //相当于给unsigned int 类型起了一个别名uint_t;
uint_t a = 100;
cout << a << endl;
typedef std::map<std::string, int> map_s_i;
map_s_i testmap;
testmap.insert({ "first", 1});
testmap.insert({ "second", 2 });
typedef std::map<std::string,std::string> map_s_s;
map_s_s testmap2;
testmap2.insert({ "first", "firstone" });
为了实现这种比较通用的以 string 类型为 key,以任意类型为 value (值)的 map 容器,我们不得不自己写一个类来达到这个目的。
/希望定义一个类型,前边这部分固定不变,std::map<std::string, 类型自己指定>
// C++98
template<typename wt>
struct map_s
{
typedef std::map<std::string, wt> type;
};
// c++11:
template<typename T>
using str_map_t = std::map<std::string,T>;
int main() {
//c++98
//相当于std::map<std::string,int> map1
map_s<int>::type map1;
map1.insert({"1",1});
//c++11
str_map_t<int>map2;
map2.insert({"1",1});
return 0;
}
using在用于定义类型(定义类型模板)的时候,是包含了 typedef 的所有功能的。
template<typename T> // using定义模板别名
using myFunc_T = int(*)(T,T);
int reakFunc(int a,int b)
{
return a+b;
}
int main() {
//using定义了类型 包含了typedef所有功能
using dd = unsigned int;
using map_s_s2 = std::map<std::string,std::string>;
typedef int(*FuncType)(int ,int);
using FuncType = int(*)(int,int);
myFunc_T<int> testFunc;// testFunc是个函数指针,是个类型名
// myFunc_T<int>是函数指针类型
testFunc = reakFunc;
cout << testFunc(1,10) << endl;
return 0;
}
using中使用这种模板,既不是类模板,也不是函数模板,我们可以看成是一种新的模板类型:类型模板(模板别名)。
二、显式指定模板参数
template<typename T1, typename T2, typename T3>
T1 sum1(T2 a, T3 b)
{
T1 result = a + b;
return result;
}
template<typename T1>
T1 sum2(T1 a, T1 b)
{
T1 result = a + b;
return result;
}
int main()
{
//auto result1 = sum1<int, string, string>(2000000000, 2000000000); //编译器直接报错
//auto result2 = sum1<double, int, int>(2000000000, 2000000000); //相加结果超过int值,得到错误答案,
auto result3 = sum1<long long, long long, long long>(2000000000, 2000000000); //手工指定的类型优先 从左到右依次指定
cout << result3 << endl;
return 0;
}