互联网@时事传播散文摄影

C++模板与泛型 --- using定义模板别名,显式指定模板参

2019-05-17  本文已影响7人  307656af5a04

上一节我们学习了 成员函数模板,显式实例化、声明,通过上一节的学习,大家对 成员函数模板,显式实例化、声明有一个比较清晰的认识,那么本节,我们继续学习模板与泛型的知识,即using定义模板别名,显式指定模板参数,希望通过本节的学习,大家能够对模板与泛型的概念有一个更加清晰的认识!

一、using定义模板别名

#include <iostream>
#include <string>
#include <map>

using namespace std;

// 希望定义一个类型,前边这部分固定不变,
// 是 std::map<std::string, 自己指定类型>
// C++98自定义类型
template <typename wt>
// 定义一个结构体/类,只是结构的成员缺省都是public
struct map_s 
{
    // 定义了一个类型
    typedef std::map<std::string, wt> type;  
};

// C++11版定义类型
template <typename T>
//str_map1是类型别名;
// using 用来给类型模板起名字用的
using str_map_t = std::map<std::string, T>; 

int main()
{
    // typedef:一般用来定义别名
    // 相当于给unsigned int类型起了一个别名uint_t
    typedef 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<string,int> map1;
    map_s<int>::type map1; 
    map1.insert({ "first",1 });

    str_map_t<int> map2;
    map2.insert({ "second",2 });

    // using在用于定义类型(定义类型模板)的时候,
    // 包含了typedef的所有功能。
    typedef unsigned int uint_tx;
    using uint_tu = unsigned int;
    
    typedef std::map<std::string, int> map_s_i;
    using map_s_u = std::map<std::string, int>;

    // 用typedef来定义函数指针
    typedef int(*FuncType)(int, int);  
    // using定一个函数指针
    using FuncType_u = int(*)(int, int);

    system("pause");
    return 0;
}
#include <iostream>
#include <string>
#include <map>

using namespace std;

// 模板函数指针
template <typename T>
using myfunc = int(*)(T, T);

// 普通的函数指针
// using myfunc = int(*)(int, int);

// 实际函数
int realFunc(int i, int j)
{
    return 1;
}

int main()
{
    // myfunc<int>是一个函数指针类型
    // pointFunc是一个函数指针变量
    myfunc<int> pointFunc;
    
    // 函数地址赋值给指针变量
    pointFunc = realFunc;
    cout << pointFunc(1, 2) << endl;
        
    // 总结:
    // 1、using中使用这种模板,既不是类模板,
    // 也不是函数模板,我们可以看成一种新的模板类型:
    // 类型模板(模板别名)

    system("pause");
    return 0;
}

二、显式指定模板参数

#include <iostream>

using namespace std;


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

int main()
{
    // 手工指定的类型优先
    // 显式指定模板类型
    auto result = sumx<double,double,double>(2000000000, 2000000000);

    cout << result << endl;

    system("pause");
    return 0;
}

我是奕双,现在已经毕业将近两年了,从大学开始学编程,期间学习了C需要编程,C++需要编程,Win32编程,MFC编程,毕业之后进入一家图像处理相关领域的公司,掌握了用OpenCV对图像进行处理,如果大家对相关领域感兴趣的话,可以关注我,我这边会为大家进行解答哦!如果大家需要相关学习资料的话,可以私聊我哦!

上一篇下一篇

猜你喜欢

热点阅读