C++11/14之using定义模板别名,显式指定模板参数

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<doubledoubledouble>(200000000, 200000000);   //显示指定返回类型,手动指定类型优先
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值