C++语法学习笔记五十九:using定义模板别名,显式指定模板参数

实例代码:

// 

#include <iostream>
#include <vector>
#include <map>

using namespace std;

//C++ 98
template <typename wt>
struct map_s{ //定义了一个结构/类,只是结构的成员缺省都是public: 
	typedef std::map <std::string, wt> type; //定义了一个类型, 键, 值
};

//C++ 11
template<typename T>
using str_map_t = std::map<std::string, T>; //str_map_t 是类型别名。
			
template<typename T>
using myfunc_M = int(*)(T, T); //定义类型模板,是个函数指针模板

int RealFunc(int i, int j){
	return 1;
}


//using 用来给一个“类型模板”起名字(别名)用的


template<typename T1, typename T2, typename T3>
T1 sum(T1 i, T3 j)
{
	T1 result = i + j;
	return result;
}


int main()
{

	//一:using定义模板别名
	//typedef : 一般用来定义类型别名
	typedef unsigned int uint_t; //相当于给unsigned int 类型起了一个别名 uint_t
	uint_t abc;
	
	//std::map<std::string, int>
	typedef std::map<std::string, int> map_s_i;
	map_s_i mymap;
	mymap.insert({ "first", 1 });
	mymap.insert({ "second", 2 });

	typedef std::map<std::string, std::string> map_s_s;
	map_s_s mymap2;
	mymap2.insert({ "first", "firstone" });

	//希望定义一个类型,前边这部分固定不变,是 std::map<std::string, 类型自己指定>
	map_s<int>::type map1; //等价于 std::map<std::string, int> map1;
	map1.insert({ "first", 1 });
	//我们为了实现这种比较通用的以string 类型为key,以任意类型为value(值)的 map容器,我们不得不自己写一个类来达到这个目的,实现手段比较猥琐。
	
	str_map_t<int> map2;
	map1.insert({ "second", 2 });

	//using 在用于定义类型(定义类型模板)的时候,是包含了typedef 的所有功能的。
	typedef unsigned int uint_t;
	using uint_t = unsigned int;

	typedef std::map<std::string, int> map_s_i;  //typedef 定义类型的方法感觉像 定义一个变量 :类型名 变量名
	using map_s_i = std::map<std::string, int>;

	typedef int(*FunType)(int, int); //用typedef来定义函数指针
	using FunType = int(*)(int, int);//using定义类型的定义方法感觉像赋值.

	myfunc_M<int> pointFunc; //myfunc_M<int> 是一个函数指针类型,是一个类型名。
							//pointFunc是一个函数指针
	pointFunc = RealFunc; //把函数地址赋给函数指针变量
	cout << pointFunc(1, 6) << endl;

	//总结:
	//using 中使用这种模板,既不是类模板,也不是函数模板,我们可以看成是一种新的模板类型:类型模板(模板别名);


	//二:显式指定模板参数
	auto result = sum<int,int>(20000, 20000);  //手工指定的类型优先
	cout << result << endl;

	system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值