C++基础学习-32using定义模板别名,显式指定模板参数

一、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;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值