4-5using定义模板别名 (模板别名 c++11),显示指定模板参数

using定义模板别名

typedef:一般用来定义类型别名

typedef unsigned int uint_t;
 
uint_t abc;
 
typedef std::map<std::string, int> map_s_i;
 
map_s_i mymap;
mymap.insert({"first", 1});
 
 
//希望定义一个类型,前边这部分固定不变,是 std::map<std::string, 类型自己指定>
template <typename wt>
struct map_s
{
    typedef std::map<std::string, wt> type;
}
 
 
map_s<int>::type map1;

我们为了实现这种比较通用的以string为类型key,以任意类型为value(值)的map容器,我们不得不自己写一个类来达到这个目的,实现手段比较猥琐。

C++11中:

template<typename T>
using str_map_t = std::map<std:string, T>;
//这里using用来给一个“类型模板”起名字
 
str_map_t<int> map2;

using用于定义类型的时候,是包含了typedef的所有功能的。

typedef unsigned int uint_t;
using uint_t = unsigned int;
 
typedef std::map<std::string, int> map_s_i;
using map_s_i = std::map<std::string, int>;
 
typedef int (*func) (int, int); //定义函数指针
using func = int (*) (int, int);

using定义类型的定义方法感觉像赋值。

typedef 定义类型的方法感觉像是定义一个变量:类名 变量名

template <typename T>
using Myfunc = int (*) (T, T);
 
int func(int a, int b){
 
}
 
int main(){
    Myfunc<int> pfunc; //Myfunc是一个函数指针类型,pfunc是一个函数指针
    pfunc = func;
 
}

总结:

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

显式指定模板参数

template <typename T1, typename T2, typename T3>
T1 sum(T2 i, T3 j){
    T1 result = i + j;
    return result;
}
 
 
int main(){
    auto result = sum<double>(2000000000, 20000000000);
    //这里T2,T3可以通过所给参数推断出类型,但是返回类型无法推断,所以需要给定
    //发现结果不对,因为结果溢出了int的最大存储,虽然指定返回double但是运算时是两个int 
    //型相加
 
    auto result = sum<double, double, double>(2000000000, 20000000000);
    auto result = sum<double, double>(2000000000, 20000000000);
    
}

using定义模板别名完整:

#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
    //c++98 :实现任意val的键值对
    //using 定义模板类名
    //type:一般定义类型别名

    //定义一个类型std::map<std::string, 类型自己定义>
    template <typename wt>
    struct map_s
    {
        typedef std::map <std::string ,wt> type;//定义了一个 ,键
    };

    //c++11实现任意val的键值对
    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;
    }
int main()
{
    //c++98
    map_s<int>::type map1;
    map1.insert({"first" ,1});
    //c++11
    str_map_t<int> map2;
    map2.insert ({"seconf" ,2});

    myFunc_M<int> pointFunc = RealFunc;
    cout << pointFunc(1,2) << endl;

    cout << "Hello world!" << endl;
    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值